-3

I have a image gallery with a css lightbox. Currently the image gallery is a masonry with lazyload. As the lightbox is a css only one all the images got loaded at the start. So I wanted to force a lazyload on it aswell. So I am trying to force a lazyload only if the image is getting used (clicked on the image in the masonry layout). After i get this working perfectly I can set the same kind of link on the previous and next icons in the lightbox.

But here is the problem. It only works the first time i click on a image. It does not matter wich image, but it only workes once :(

I tried several things but none seems to work.

But the issue remains.

Javascript jquery

$(function() {
    $("#image-link").on('click', function() {
        var counter = $(this).data('target');
        $('.lazybox-' + counter).lazy();
    });
});

Html = the counter is to force the lazyload on the specific image

<a id="image-link" href="#<?php echo $id; ?>" data-target="<?php echo $counter; ?>">
   <img class="lazy" src=/images/placeholder" data-src="<?php echo base_url($imageLocation); ?>" alt="<?php echo $selected_gallery . ' ' . $counter; ?>">
</a>

I would like to be able to use the javascript function more then once. If at all possible explain why it happend so I can learn, I am a true beginner if it comes to javascript.

  • Are you dynamically replacing the `#image-link` at any point? And you only have one element on the page with the id of `image-link` I assume? – Taplar Aug 23 '19 at 18:54
  • 1
    Try: `$(document).on('click', '#image-link', function(){` – vsync Aug 23 '19 at 18:56
  • @vsync I'm trying to get there with the comments. If that's the issue (most likely it is), this is a duplicate. – Taplar Aug 23 '19 at 18:57
  • *"Changing the jquery click() to on('click', function()"* - Can you be more specific about what you changed from and to? `.on()` is not a magic wand. If the element holding the event handler is replaced then it's going to fail for exactly the same reason as `.click()` did. – David Aug 23 '19 at 18:57
  • 2
    `click(function(){})` to `on('click', function(){})` is the same exact thing – epascarello Aug 23 '19 at 18:58
  • No i have multiple #image-links on the page. Actualy every image has the same id. Thats why I give along the data-target I forgot to mention I am a beginner at javascript – Pieter-Jan Casteels Aug 23 '19 at 19:05
  • 3
    Id's must be unique or else only the first element will have the event so try giving them a unique id and use a class instead $('.class').on('click', function() {}); Also your "src" is missing quotes. – VVV Aug 23 '19 at 19:07

1 Answers1

-1

Ok I feel realy stupid. But the solution was pretty simple.

Don't use a ID #image-link but use a CLASS .image-link