How to trigger a click on a link using jQuery

Patrioticcow picture Patrioticcow · Apr 27, 2011 · Viewed 671.6k times · Source

I have a link:

<ul id="titleee" class="gallery">
  <li>
    <a href="#inline" rel="prettyPhoto">Talent</a>
  </li>
</ul>

and I am trying to trigger it by using:

$(document).ready(function() {
  $('#titleee').find('a').trigger('click');
});

But it doesn't work.

I've also tried: $('#titleee a').trigger('click');

Edit:

I actually need to trigger whatever get's called here <a href="#inline" rel="prettyPhoto">

Answer

Kit Sunde picture Kit Sunde · Apr 28, 2011

If you are trying to trigger an event on the anchor, then the code you have will work I recreated your example in jsfiddle with an added eventHandler so you can see that it works:

$(document).on("click", "a", function(){
    $(this).text("It works!");
});

$(document).ready(function(){
    $("a").trigger("click");
});

Are you trying to cause the user to navigate to a certain point on the webpage by clicking the anchor, or are you trying to trigger events bound to it? Maybe you haven't actually bound the click event successfully to the event?

Also this:

$('#titleee').find('a').trigger('click');

is the equivalent of this:

$('#titleee a').trigger('click');

No need to call find. :)