94

I'm trying to trigger click event on hyperlink with jQuery like the way below. Hyperlink does not have any id but it does have css class:

$(document).ready(function () {  
  $('.cssbuttongo').trigger('click'); 
}); 

The function above is not working. This is the hyperlink:

<a href="hyperlinkurl" class="cssbuttongo">hyperlink anchor</a>
Asef Hossini
  • 655
  • 8
  • 11
Furkan Gözükara
  • 22,964
  • 77
  • 205
  • 342

6 Answers6

234

The native DOM method does the right thing:

$('.cssbuttongo')[0].click();
                  ^
              Important!

This works regardless of whether the href is a URL, a fragment (e.g. #blah) or even a javascript:.

Note that this calls the DOM click method instead of the jQuery click method (which is very incomplete and completely ignores href).

Roman Starkov
  • 59,298
  • 38
  • 251
  • 324
  • @LinDong: Please provide a link to a JsFiddle that contains the text `[0].click()` which does not work as expected. – Timwi Jun 07 '14 at 15:01
  • 2
    @Timwi, I meant to say the first one `$('.cssbuttongo').click(); // ignores href!` won't guarantee to work. The latter one will always work, because using index [0] will make jQuery Object to regular JS Object which is exactly the same one browser uses. @Wei Liu – Alan Dong Jun 11 '14 at 23:13
  • @LinDong: That’s exactly what this answer is saying! – Timwi Jun 12 '14 at 08:10
  • @LinDong OK, I see where the confusion was. You were looking at my example of what doesn't work and saying that it doesn't work. I've removed that example; it wasn't even needed in the first place. – Roman Starkov Jun 12 '14 at 11:28
  • @trainoasis You sure about "target"? [Seems to work](http://jsfiddle.net/h77f74LL/2/). Haven't tested "download". – Roman Starkov Nov 20 '14 at 17:47
  • hmm, didn't work in my case, that is strange indeed. download attr in html5 supported browsers did not fire as expected. unfortunately – trainoasis Nov 21 '14 at 06:55
  • `click()` is a jQuery function, while `$('.cssbuttongo')[0]` won't return a jQuery object. This should throw an error. I don't know how it's working for so many people. The correct syntax should be this: `$($('.cssbuttongo')[0]).click()` – Adil Malik Sep 23 '15 at 17:09
  • 3
    @AdilMalik It works because jquery is not the only thing that has a click() method. This code calls the non-jquery click() method, it's a native DOM thing. – Roman Starkov Sep 23 '15 at 17:10
  • @romkyns I see. But I just tried it. It's giving me `undefined` error. Must be something wrong on my end, because many people are testifying that your solution is working for them :-) – Adil Malik Sep 23 '15 at 17:54
  • 1
    @Timwi I provide jsfiddle in here: https://jsfiddle.net/NabiKAZ/3gv90od5/ – Nabi K.A.Z. Sep 04 '17 at 00:11
  • It works! In some case someone looking for a code I'll add this $(' #.cssbuttongo a').first()[0].click(); if you want to click the first child :) – mrrsb Oct 09 '18 at 01:46
83

I do not have factual evidence to prove this but I already ran into this issue. It seems that triggering a click() event on an <a> tag doesn't seem to behave the same way you would expect with say, a input button.

The workaround I employed was to set the location.href property on the window which causes the browser to load the request resource like so:

$(document).ready(function()
{
      var href = $('.cssbuttongo').attr('href');
      window.location.href = href; //causes the browser to refresh and load the requested url
   });
});

Edit:

I would make a js fiddle but the nature of the question intermixed with how jsfiddle uses an iframe to render code makes that a no go.

Matthew Cox
  • 13,566
  • 9
  • 54
  • 72
34

In addition to romkyns's great answer.. here is some relevant documentation/examples.


DOM Elements have a native .click() method.

The HTMLElement.click() method simulates a mouse click on an element.

When click is used, it also fires the element's click event which will bubble up to elements higher up the document tree (or event chain) and fire their click events too. However, bubbling of a click event will not cause an <a> element to initiate navigation as if a real mouse-click had been received. (mdn reference)

Relevant W3 documentation.


A few examples..

  • You can access a specific DOM element from a jQuery object: (example)

      $('a')[0].click();
    
  • You can use the .get() method to retrieve a DOM element from a jQuery object: (example)

      $('a').get(0).click();
    
  • As expected, you can select the DOM element and call the .click() method. (example)

      document.querySelector('a').click();
    

It's worth pointing out that jQuery is not required to trigger a native .click() event.

Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
4

Triggering a click via JavaScript will not open a hyperlink. This is a security measure built into the browser.

See this question for some workarounds, though.

Community
  • 1
  • 1
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • 1
    I don't think so.. BECAUSE : **I FOUND ITS WORKING LIKE THIS** .. Follow the [jsfiddle here](http://jsfiddle.net/8AVau/2/) – Cody Jan 05 '14 at 03:09
  • 3
    @CodyDmd that's still a user-triggered click event taking place. Not the same thing as OP's original question. – Blazemonger Jan 05 '14 at 06:25
  • @CodyDmd It seems that `[0]` is important in your fiddle – Wei Liu Jan 29 '14 at 08:01
  • 3
    What vulnerability does that protect against, exactly? – Roman Starkov Feb 13 '14 at 17:53
  • @romkyns Triggering downloads, or SEO click fraud. – Blazemonger Feb 13 '14 at 19:03
  • @CodyDmd Look at your JSFiddle `target="_blank"` – Mathew Kurian May 19 '14 at 15:55
  • @Blazemonger i updated the jsfiddle, thanks for your info. is this the way OP is asking? http://jsfiddle.net/8AVau/60/ – Cody May 20 '14 at 02:45
  • @mk1 i just added target attribute for the demonstration purpose.. please check it out the updated jsfiddle here http://jsfiddle.net/8AVau/60/ – Cody May 20 '14 at 02:47
  • 3
    Well I don't know what you mean, Blazemonger, because there is no such protection against downloads or SEO click fraud in Firefox, nor Chrome, nor IE11. In other words, both the first and the second sentence of your answer [are false](http://jsfiddle.net/4kAxm/9/). – Roman Starkov Jun 07 '14 at 14:39
3

Just want to let you guys know, the accepted answer doesn't always work.

Here's an example it will fail.

if <href='/list'>

href = $('css_selector').attr('href')
"/list"
href = document.querySelector('css_selector').href
"http://localhost/list"

or you could append the href you got from jQuery to this

href = document.URL +$('css_selector').attr('href');

or jQuery way

href = $('css_selector').prop('href')

Finally, invoke it to change the browser current page's url

window.location.href = href

or pop it out using window.open(url)

Here's an example in JSFiddle.

Alan Dong
  • 3,981
  • 38
  • 35
  • So you're saying this doesn't work if you change it to `$('css_selector')[0].click()`? It works in [this JsFiddle](http://jsfiddle.net/4kAxm/5/)... – Roman Starkov Jun 07 '14 at 14:34
  • For the record, it wasn't me who downvoted; I think there may be something here and I'm not sure yet. – Roman Starkov Jun 07 '14 at 15:06
  • @romkyns, Of course, it's going to work after you extract from jQuery elements using[0] (It becomes pure JS), I meant to say `$('.cssbuttongo').click();` won't work because it only gives whatever the value of href, instead of the URL of the browser uses. Sorry about the misleading comments. – Alan Dong Jun 11 '14 at 23:05
  • 2
    @LinDong: If you **know** that `[0].click()` works, why does your answer not mention that? – Timwi Jun 12 '14 at 08:13
  • `location.href` accepts relative paths, so using `/list` will automatically prepend the current domain. So it does work. – Tim Oct 09 '18 at 13:51
-1

I was facing a similar issue how to click a button, instead of a link. It did not success in the methods .trigger('click') or [0].click(), and I did not know why. At last, the following was working for me:

$('#elementid').mousedown();
Henry
  • 1,077
  • 1
  • 16
  • 41