Simulate a click on 'a' element using javascript/jquery

245,631

Solution 1

Using jQuery: $('#gift-close').trigger('click');

Using JavaScript: document.getElementById('gift-close').click();

Solution 2

Using jQuery:

$('#gift-close').click();

Solution 3

Try to use document.createEvent described here https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent

The code for function that simulates click should look something like this:

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var a = document.getElementById("gift-close"); 
  a.dispatchEvent(evt);      
}

Solution 4

Code snippet underneath!

Please take a look at these documentations and examples at MDN, and you will find your answer. This is the propper way to do it I would say.

Creating and triggering events

Dispatch Event (example)

Taken from the 'Dispatch Event (example)'-HTML-link (simulate click):

function simulateClick() {

  var evt = document.createEvent("MouseEvents");

  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);

  var cb = document.getElementById("checkbox"); 
  var canceled = !cb.dispatchEvent(evt);

  if(canceled) {
    // A handler called preventDefault
    alert("canceled");
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");
  }
}

This is how I would do it (2017 ..) :

Simply using MouseEvent.

function simulateClick() {

    var evt = new MouseEvent("click");

    var cb = document.getElementById("checkbox");
    var canceled = !cb.dispatchEvent(evt);

    if (canceled) {
        // A handler called preventDefault
        console.log("canceled");
    } else {
        // None of the handlers called preventDefault
        console.log("not canceled");
    }
}

document.getElementById("button").onclick = evt => {
    
    simulateClick()
}

function simulateClick() {

    var evt = new MouseEvent("click");

    var cb = document.getElementById("checkbox");
    var canceled = !cb.dispatchEvent(evt);

    if (canceled) {
        // A handler called preventDefault
        console.log("canceled");
    } else {
        // None of the handlers called preventDefault
        console.log("not canceled");
    }
}
<input type="checkbox" id="checkbox">
<br>
<br>
<button id="button">Check it out, or not</button>

Solution 5

The code you've already tried:

document.getElementById("gift-close").click();

...should work as long as the element actually exists in the DOM at the time you run it. Some possible ways to ensure that include:

  1. Run your code from an onload handler for the window. http://jsfiddle.net/LKNYg/
  2. Run your code from a document ready handler if you're using jQuery. http://jsfiddle.net/LKNYg/1/
  3. Put the code in a script block that is after the element in the source html.

So:

$(document).ready(function() {
    document.getElementById("gift-close").click();
    // OR
    $("#gift-close")[0].click();
});
Share:
245,631

Related videos on Youtube

user2373137
Author by

user2373137

Updated on July 08, 2022

Comments

  • user2373137
    user2373137 almost 2 years

    I am trying to simulate a click on on an element. HTML for the same is as follows

    <a id="gift-close" href="javascript:void(0)" class="cart-mask-close p-abs" onclick="_gaq.push(['_trackEvent','voucher_new','cart',$(this).attr('rel')+'-mask_x_button-inaction']);" rel="coupon">&nbsp;</a>
    

    How can i simulate a click on it. I have tried

    document.getElementById("gift-close").click();

    But its not doing anything

    • nnnnnn
      nnnnnn almost 11 years
      Where are you doing document.getElementById("gift-close").click(); from? It will work if you do it from an onload handler (or otherwise ensure the <a> element exists): jsfiddle.net/LKNYg
    • mekwall
      mekwall almost 11 years
      If you are really using jQuery, this is one of the most basic things you learn first. Please check out jQuery Fundamentals to learn more.
    • user2373137
      user2373137 almost 11 years
      I want to make the inline onclick handler execute
    • AmerllicA
      AmerllicA about 7 years
      Please, just please do not write href="javascript:void(0)". It has critical SEO issues.
    • Sunil Kumar
      Sunil Kumar over 4 years
      Please note that user-click and triggered programmed click work differently. stackoverflow.com/questions/11127908/…
  • nnnnnn
    nnnnnn almost 11 years
    Why would that work when document.getElementById("gift-close").click(); didn't?
  • Alex Guerra
    Alex Guerra almost 11 years
    Because document.getElementById("gift-close") is not a jQuery object but a DOM object. You could try this too: $(document.getElementById("gift-close")).click();
  • nnnnnn
    nnnnnn almost 11 years
    @techfoobar and Alex, DOM elements have a .click() method. jsfiddle.net/LKNYg
  • techfoobar
    techfoobar almost 11 years
    @nnnnnn - Wow! Totally new info for me.. Never knew that.. Tks :-)
  • nnnnnn
    nnnnnn almost 11 years
    Why would that work when document.getElementById("gift-close").click(); didn't?
  • Alex Guerra
    Alex Guerra almost 11 years
    Oh, yes. You're right. Then the problem is that he should execute click code after page loading, i.e. in onReady event ;)
  • nnnnnn
    nnnnnn almost 11 years
    @roasted - It did fire the inline onclick for me in Chrome: jsfiddle.net/LKNYg/2 (but from past experience I believe it wouldn't cause actual navigation if it was a "proper" anchor with an href containing a URL).
  • A. Wolff
    A. Wolff almost 11 years
    @nnnnnn you are right! Just the native behaviour of anchor tag is not fired, my bad!
  • user2373137
    user2373137 almost 11 years
    I want to make the inline onclick handler execute
  • user2373137
    user2373137 almost 11 years
    I want to make the inline onclick handler execute
  • nnnnnn
    nnnnnn almost 11 years
    Right. And that happens in both of the jsfiddle demos I provided.
  • ihor marusyk
    ihor marusyk almost 11 years
    Also look at this question stackoverflow.com/questions/15951468/… this describes newer approach to creating custom events.
  • Farid Imranov
    Farid Imranov almost 11 years
    You have to run your code from onload handler for javascript, or $(document).ready(function(){//write code here}) for JQuery
  • 425nesp
    425nesp almost 10 years
    document.getElementById('gift-close').onClick(); doesn't work in Chrome, Firefox, or Safari. However, changing onClick() to click() does work.
  • Hugo Zink
    Hugo Zink almost 8 years
    Didn't the asker explicity say that this doesn't work? I don't understand the upvotes.
  • André Dion
    André Dion almost 8 years
    @HugoZink because it does work..? Did you try anything before downvoting/commenting?
  • Hugo Zink
    Hugo Zink almost 8 years
    @AndréDion I did, and it does not seem to work in Firefox. Probably due to security concerns.
  • Humayun
    Humayun about 7 years
    Wow awesom! I just tried your solution to upvote your answer and it really works:) If anyone want to try? Do this in console.... var evt = document.createEvent("MouseEvents"); evt.initMouseEvent("click", true, true, window,0, 0, 0, 0, 0, false, false, false, false, 0, null); var a = $('div#answer-17569610 a.vote-up-off').get(0); a.dispatchEvent(evt);
  • Ellert van Koperen
    Ellert van Koperen over 6 years
    Change "document.createEvent" to "new CustomEvent" to conform to new standards. This is the better solution, as it realy simulates a click, which sometimes is not the same as simply firing the onClick event. Especially if the element is doing 2 things, like opening a link (in a new window?) and handling the Click event (to do something on the same page). Thanks Ihor.
  • user2986756
    user2986756 over 3 years
    The trick I found (compared to the "best" answer) was to use the [0]. That caused the script to work.
  • Aditya
    Aditya over 2 years
    Shouldn't Be used any more because of Jquery 3.6.0 it's outdated.
  • Tudor
    Tudor about 2 years
    this is a click event listener, not a click event trigger