0

Is there a way to target the img showed in lightgallery.js slider ?

This JS below has 3 fails to get a simple console.log(); :

var $lg = $('#mosaic');
$lg.lightGallery({thumbnail: false, addClass: 'imgGallery'});

$('.imgGallery img').click(function() {
     console.log('click'); // fail
});
$('img.lg-object.lg-image').click(function() {
     console.log('click'); // fail
});
$('div.lg-img-wrap img').click(function() {
     console.log('click'); // fail
});

JSFIDDLE

j08691
  • 204,283
  • 31
  • 260
  • 272
Joe278
  • 105
  • 1
  • 7

1 Answers1

1

The img elements that have the click event aren't inside the .imgGallery div. They're actually inside of #mosaic. If you change that selector to $('#mosaic img') you're all set for that one.

As for the other two, those elements are created dynamically, so they don't exist at the time you're trying to bind the click events. What you want is click delegation, so that you're binding the click event to an outer element, but intercepting it on a child. So create a wrapper around everything (or if not possible, bind to the body)

$('body').click('img.lg-object.lg-image', function(e) {
 console.log('click'); // success
 console.log(this); // body (element to which the event is bound)
 console.log(e.target); // img.lg-object.lg-image (element that received the click)
});
jmcgriz
  • 2,819
  • 1
  • 9
  • 11