How to trigger click event on href element

318,674

Solution 1

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.

Solution 2

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

Solution 3

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.

Solution 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.

Solution 5

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.

Share:
318,674
MonsterMMORPG
Author by

MonsterMMORPG

Hello. I am the only owner and developer of web based online MMORPG game MonsterMMORPG. I am a computer engineer from Turkey and i am currently doing MA at computer engineering. I am specialized with C# &amp; ASP.net. http://www.monstermmorpg.com/ MonsterMMORPG is a Free To Play Browser Based Online Monster MMORPG Game Better Than Online Pokemon Games You will love it's awesome Monsters We have many different unique features. So i suggest you to check them out. Our game is similiar with Pokemon games but it is unique. Like diablo and torch light. You should visit following sites related to us MonsterMMORPG Facebook Pokemon Games Lovers Facebook Application MonsterMMORPG Youtube Channel Monster Game Forum Canavar Oyunu Forum Pokemon Fakemon DeviantArt MonsterMMORPG Google Plus MonsterMMORPG Twitter MonsterMMORPG Review On Browsergamez MonsterMMORPG Review On mmohuts MonsterMMORPG Developer Blog At MMORPG.com MonsterMMORPG Review On onrpg MonsterMMORPG On GameSpot MonsterMMORPG Wiki MonsterMMORPG On 1UP MonsterMMORPG Digg MonsterMMORPG Official Google Plus Page

Updated on July 08, 2022

Comments

  • MonsterMMORPG
    MonsterMMORPG almost 2 years

    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>
    
  • MonsterMMORPG
    MonsterMMORPG over 12 years
    this is the correct answer. thank you :) i also noticed that click on href does not work.
  • Matthew Cox
    Matthew Cox over 12 years
    @MonsterMMorpg Keep in mind that this does not result in the browser believing that it is direct user action. So use wisely =D
  • Luci
    Luci over 11 years
    Shouldn't it be var href = $('.cssbuttongo').attr('href');
  • Cody
    Cody over 10 years
    I don't think so.. BECAUSE : I FOUND ITS WORKING LIKE THIS .. Follow the jsfiddle here
  • Blazemonger
    Blazemonger over 10 years
    @CodyDmd that's still a user-triggered click event taking place. Not the same thing as OP's original question.
  • Wei Liu
    Wei Liu over 10 years
    @CodyDmd It seems that [0] is important in your fiddle
  • Roman Starkov
    Roman Starkov over 10 years
    What vulnerability does that protect against, exactly?
  • Roman Starkov
    Roman Starkov over 10 years
    This ignores the possibility that the link also has an onclick event. Just do $('.cssbuttongo')[0].click() to properly simulate a click in its entirety.
  • Blazemonger
    Blazemonger over 10 years
    @romkyns Triggering downloads, or SEO click fraud.
  • Mathew Kurian
    Mathew Kurian almost 10 years
    @CodyDmd Look at your JSFiddle target="_blank"
  • Cody
    Cody almost 10 years
    @Blazemonger i updated the jsfiddle, thanks for your info. is this the way OP is asking? jsfiddle.net/8AVau/60
  • Cody
    Cody almost 10 years
    @mk1 i just added target attribute for the demonstration purpose.. please check it out the updated jsfiddle here jsfiddle.net/8AVau/60
  • Alan Dong
    Alan Dong almost 10 years
    Actually it works only on the complete href. Since I couldn't put code here, please read my answer to this post.
  • Roman Starkov
    Roman Starkov almost 10 years
    So you're saying this doesn't work if you change it to $('css_selector')[0].click()? It works in this JsFiddle...
  • Roman Starkov
    Roman Starkov almost 10 years
    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.
  • ssss
    ssss almost 10 years
    @LinDong: Please provide a link to a JsFiddle that contains the text [0].click() which does not work as expected.
  • Roman Starkov
    Roman Starkov almost 10 years
    For the record, it wasn't me who downvoted; I think there may be something here and I'm not sure yet.
  • Alan Dong
    Alan Dong almost 10 years
    @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
    Alan Dong almost 10 years
    @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
  • ssss
    ssss almost 10 years
    @LinDong: That’s exactly what this answer is saying!
  • ssss
    ssss almost 10 years
    @LinDong: If you know that [0].click() works, why does your answer not mention that?
  • Roman Starkov
    Roman Starkov almost 10 years
    @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.
  • caiosm1005
    caiosm1005 almost 10 years
    Awesome! Very direct and illustrative answer.
  • Roman Starkov
    Roman Starkov over 9 years
    @trainoasis You sure about "target"? Seems to work. Haven't tested "download".
  • trainoasis
    trainoasis over 9 years
    hmm, didn't work in my case, that is strange indeed. download attr in html5 supported browsers did not fire as expected. unfortunately
  • Amit G
    Amit G over 9 years
    This should be the selected answer. Worked perfectly!
  • pat capozzi
    pat capozzi over 8 years
    A tiny bit of brilliance
  • Adil Malik
    Adil Malik over 8 years
    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()
  • Roman Starkov
    Roman Starkov over 8 years
    @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.
  • Adil Malik
    Adil Malik over 8 years
    @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 :-)
  • Nabi K.A.Z.
    Nabi K.A.Z. over 6 years
    @Timwi I provide jsfiddle in here: jsfiddle.net/NabiKAZ/3gv90od5
  • mrrsb
    mrrsb over 5 years
    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 :)
  • Tim
    Tim over 5 years
    location.href accepts relative paths, so using /list will automatically prepend the current domain. So it does work.