Specific image in a modal window

Asked

Viewed 157 times

1

I have a code that takes all images from a directory:

<script>

	var folder = "img/";
	$.ajax({
		url: folder,
		success: function (data) {
			$(data).find("a").attr("href", function (i, val) {
				if (val.match(/\.(jpe?g|png|gif)$/)) {
					$(".columns").append("<div class = 'column is-4' > <a data-target = 'modal_name'class = 'img-input'> <img id = 'img-card' src='" + folder + val + "'></a></div>");
				}
			});
		}
	});

</script>

And when I click on the image, opens a modal window, I would like it to open this modal with the specific image that I click on...is there how? I have no idea.

  • https://pastebin.com/d3yDMqD5 full page

1 answer

0


Don’t use the event window.onload because it is asynchronous with Ajax. Inside it you are trying to assign click events to images that will only be returned after Ajax. thus, the result.onclick will not find the images at runtime.

Change the window.onload to a normal function and call it after the return of Ajax.

Alter:

window.onload = () => {
   ...
}

for:

var Load = () => {
   document.querySelectorAll('[data-target]').forEach((result) => {
      result.onclick = (e) => {
         document.querySelector(".modal-card-body").innerHTML = e.target.outerHTML;
         let modal = document.getElementById(result.getAttribute('data-target'))
         modal.classList.toggle("is-active")
         modal.querySelector('.delete').onclick = () => { modal.classList.toggle("is-active") }
      }
   })
}

See that in the result.onclick includes a parameter (e) to take the image clicked and play it in the modal with:

document.querySelector(".modal-card-body").innerHTML = e.target.outerHTML;

In Ajax, call the function Load() at the end of success:

var folder = "img/";
$.ajax({
   url: folder,
   success: function (data) {
      $(data).find("a").attr("href", function (i, val) {
         if (val.match(/\.(jpe?g|png|gif)$/)) {
            $(".columns").append("<div class = 'column is-4' > <a data-target = 'modal_name'class = 'img-input'> <img id = 'img-card' src='" + folder + val + "'></a></div>");
         }
      });
      Load();
   }
});
  • 1

    Thank you so much! It Works

Browser other questions tagged

You are not signed in. Login or sign up in order to post.