Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call click() for element?

I am using a lightgallery plugin where the click event is defined as:

$(document).on('click', 'a[rel^=lightbox], area[rel^=lightbox], a[data-lightbox], area[data-lightbox]', function(event) {
    self.start($(event.currentTarget));
    event.preventDefault();
});

However, when I try to call the event like this:

$(".catalog-content a[data-lightbox='test']").first().trigger('click');

... it doesn't seem to work. What am I doing wrong? How can I trigger the click event?

Example jsFiddle

like image 625
Buboon Avatar asked Nov 11 '22 04:11

Buboon


1 Answers

To "simulate a click" using jQuery, you are correct in that you can just use the .trigger(...) method:

$(".myClass").trigger("click");

The real issue is that you are "clicking" something that doesn't exist. There is no ".catalog-content a[data-lightbox='test' element. As Velthune suggests, you can add the .catalog-content class to the div container to fix this; however, note that there also is no a[data-lightbox='test'] element.

Instead, in your Fiddle you define the following:

<a href="http://..." data-lightbox="350xi" id="test">
    something
</a>

So you actually just want to click on the first a element with a data-lightbox attribute of "350xi":

$("a[data-lightbox='350xi']").first().trigger("click");
like image 79
Casey Falk Avatar answered Nov 15 '22 08:11

Casey Falk