Specific image in a modal window

1

I have a code that takes all the images in 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, it opens a modal window, I would like it to open this modal with the specific image I click on ... there is how? I have no idea.

    
asked by anonymous 24.05.2018 / 01:13

1 answer

0

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

Change window.onload to a normal function and call it after Ajax returns.

Change:

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

To:

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") }
      }
   })
}

Note that in result.onclick I include a (e) parameter to get the clicked image and play it in 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();
   }
});
    
24.05.2018 / 02:03