306

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

Deanna
  • 23,876
  • 7
  • 71
  • 156
Patrioticcow
  • 26,422
  • 75
  • 217
  • 337
  • 8
    `location.href($('#titleee').find('a').attr("href"));` ? – Sylvain Apr 27 '11 at 22:02
  • 4
    or even $('ul.gallery').find('li>a').trigger('click'); – Phil C Apr 27 '11 at 22:03
  • 141
    Guys. The real answer is so simple. `$('#titleee a')[0].click();`. In other words, use the DOM click method, not the jQuery one. Upvote [Graham Hotchkiss](http://stackoverflow.com/a/21334234/33080)! – Roman Starkov Feb 13 '14 at 18:23
  • 6
    @romkyns no its not right as its opening a pop up instead of new tab. but clicking on a dummy span inside this 'a' tag serves the purpose – Shishir Arora Jul 19 '15 at 01:45
  • 2
    If you are trying to trigger an event on the anchor, then the code you have will work.`$('ul#titleee li a[href="#inline"]').click();` – Anand Pal Aug 23 '18 at 10:32
  • upvoted Roman Starkov's comment: if it is rails_ujs like: $('a.show').on("ajax:success"), triggering a click only works using the DOM element click() function – walt_die Aug 31 '18 at 12:09

12 Answers12

369

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. :)

Kit Sunde
  • 35,972
  • 25
  • 125
  • 179
  • 21
    @Kit .find() is a faster selector than what you are proposing, do a benchmark if you disagree but your proposal slows it down. positively :-) – Ady Ngom Apr 27 '11 at 22:22
  • 15
    @mashappslabs - That's okay. I'm happy for you if you feel the need to do premature and micro optimizations, no matter how true it is. :) – Kit Sunde Apr 27 '11 at 22:34
  • 7
    @Kit... so when you are making a statement such as "no need to call find", it does not fall into the realm of premature optimization?? I think it does but it just happens to be slower than what was proposed at first. I'm not responding for the sake of argument, but for a concerted effort to get better at what we all love doing. I hope this comes out right :-) – Ady Ngom Apr 27 '11 at 22:45
  • @mashappslabs - It doesn't qualify because that's how you would normally type that selector, it's the default case. Someone who don't write code like that are probably unaware you can chain in a selector. I would for that matter be very surprised if it was slower as a general case and especially in browsers with a native query selector, but I reject your call for me to prove you wrong without you first supplying proof, on the basis of the null hypothesis. I also think it's the compilers (jQuerys) issue to deal with at this abstraction layer, unless it's a practical issue in the single case. – Kit Sunde Apr 27 '11 at 23:28
  • 5
    @mashappslabs - Having seen jsperf.com for the first time I thought I'd come back and say you are right, your method is faster in the general case. Only Opera is slower. http://jsperf.com/jquery-selector-perf-right-to-left/32 – Kit Sunde Apr 28 '11 at 04:50
  • you know what is funny @Kit, we have the exact same tumblr theme, how random is that, I haven't updated mine in a while but I thought it was very random. Anyways I will add jsperf to my toolkit. Cheers :-) – Ady Ngom Apr 28 '11 at 05:19
  • 10
    Oddly, the above does not work for me, but @GrahamHotchkiss answer does. – Oliver Aug 07 '14 at 01:23
  • @Schollii Probably because you are selecting an array of elements (even if only one is found), and `[0]` selects the first element in that array. – rybo111 Mar 16 '16 at 23:43
  • Btw, the .live() doesn't work on the latest version of jQuery. You can use .on() instead. – Anthony Feb 01 '18 at 16:25
  • So many upvotes for an answer that neither works nor answers the question... See Alex' answer below instead! – jlh Dec 13 '19 at 08:57
264

Sorry, but the event handler is really not needed. What you do need is another element within the tag to click on.

<a id="test1" href="javascript:alert('test1')">TEST1</a>
<a id="test2" href="javascript:alert('test2')"><span>TEST2</span></a>

Jquery:

$('#test1').trigger('click'); // Nothing
$('#test2').find('span').trigger('click'); // Works
$('#test2 span').trigger('click'); // Also Works

This is all about what you are clicking and it is not the tag but the thing within it. Unfortunately, bare text does not seem to be recognised by JQuery, but it is by vanilla javascript:

document.getElementById('test1').click(); // Works!

Or by accessing the jQuery object as an array

$('#test1')[0].click(); // Works too!!!
Graham Hotchkiss
  • 2,649
  • 1
  • 11
  • 3
  • 13
    $('selector')[0].click() will actually handle at least one case that triggering the event handler will not: having the browser recognize it as an actual click for triggering a protocol handler link. Calling trigger on the click event will not cause the associated application to launch. Thanks for including it in your answer! – Greg Pettit Apr 23 '14 at 16:04
  • 4
    Yep, `.click()` is precisely what I needed! – notacouch Oct 17 '14 at 17:10
  • 3
    $('#test2 span').trigger('click'); helped as it can open a url in new tab but $('#test1')[0].click(); was opening a pop up instea. – Shishir Arora Jul 19 '15 at 01:43
  • When I try to handle click on background element: $('#titleee a').trigger('click'); -> Doesn't work! $('#titleee a')[0].click(); -> Works! – 18augst Mar 28 '17 at 09:58
  • 3
    $('#test1')[0].click(); is a saviour. Thanks a lot – Amit Bisht Sep 21 '17 at 21:21
  • document.getElementById('test1').click(); -- is the right answer – Nigel Fds May 17 '19 at 02:41
  • note that .click() method works only if data-trigger="click" is set not "focus" – luky Dec 28 '21 at 13:58
64

Since this question is ranked #1 in Google for "triggering a click on an <a> element" and no answer actually mentions how you do that, this is how you do it:

$('#titleee a')[0].click();

Explanation: you trigger a click on the underlying html-element, not the jQuery-object.

You're welcome googlers :)

Alex from Jitbit
  • 53,710
  • 19
  • 160
  • 149
8

If you are trying to trigger an event on the anchor, then the code you have will work.

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

OR

$(document).ready(function() {
  $('#titleee li a[href="#inline"]').click();
});

OR

$(document).ready(function() {
  $('ul#titleee li a[href="#inline"]').click();
});
Anand Pal
  • 101
  • 1
  • 5
7

With the code you provided, you cannot expect anything to happen. I second @mashappslabs : first add an event handler :

$("selector").click(function() {
    console.log("element was clicked"); // or alert("click");
});

then trigger your event :

$("selector").click(); //or
$("selector").trigger("click");

and you should see the message in your console.

Julz
  • 384
  • 2
  • 7
  • 8
    This does not work for me: if selector is "a" (HTML tag for links, just to be clear), the anonymous function gets called when I call `trigger`, but the tag's action does not happen. It's like the event does not propagate to the associated DOM element. The answer by @GrahamHotchkiss is the only one that works reliably for me. – Oliver Aug 07 '14 at 01:23
6

Well you have to setup the click event first then you can trigger it and see what happens:

//good habits first let's cache our selector
var $myLink = $('#titleee').find('a');
$myLink.click(function (evt) {
  evt.preventDefault();
  alert($(this).attr('href'));
});

// now the manual trigger
$myLink.trigger('click');
Ady Ngom
  • 1,284
  • 2
  • 10
  • 12
4

This is the demo how to trigger event

<!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("input").select(function(){
            $("input").after(" Text marked!");
        });
        $("button").click(function(){
            $("input").trigger("select");
        });
    });
    </script>
    </head>
    <body>

    <input type="text" value="Hello World"><br><br>

    <button>Trigger the select event for the input field</button>

    </body>
    </html>
Harshad Hirapara
  • 462
  • 3
  • 12
2

This doesn't exactly answer your question, but will get you the same result with less headache.

I always have my click events call methods that contain all the logic I would like to execute. So that I can just call the method directly if I want to perform the action without an actual click.

Matthew Vines
  • 27,253
  • 7
  • 76
  • 97
1

You should call the element's native .click() method or use the createEvent API.

For more info, please visit: https://learn.jquery.com/events/triggering-event-handlers/

Marcello B.
  • 4,177
  • 11
  • 45
  • 65
  • 6
    Welcome to Stack Overflow! While this might be a valuable hint to solve the problem, a good answer also demonstrates the solution. Please [edit] to provide example code to show what you mean. Alternatively, consider writing this as a comment instead. – Toby Speight May 30 '17 at 11:13
1

For links this should work:

eval($(selector).attr('href'));
Marcello B.
  • 4,177
  • 11
  • 45
  • 65
Amin
  • 422
  • 4
  • 4
1

We can do it in many ways...

CASE - 1

We can use trigger like this : $("#myID").trigger("click");

CASE - 2

We can use click() function like this : $("#myID").click();

CASE - 3

If we want to write function on programmatically click then..

$("#myID").click(function() {
  console.log("Clicked");
// Do here whatever you want
});

CASE - 4

// Triggering a native browser event using the simulate plugin
$("#myID").simulate( "click" );  

Also you can refer this : https://learn.jquery.com/events/triggering-event-handlers/

Rohit Tagadiya
  • 3,373
  • 1
  • 25
  • 25
0

Shortest answer:

$('#titlee a').click();
Sam
  • 105
  • 2
  • 14