95

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

5
  • 1
    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 Commented Jul 10, 2013 at 11:06
  • 2
    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. Commented Jul 10, 2013 at 11:08
  • I want to make the inline onclick handler execute Commented Jul 10, 2013 at 11:26
  • Please, just please do not write href="javascript:void(0)". It has critical SEO issues. Commented Apr 15, 2017 at 11:38
  • Please note that user-click and triggered programmed click work differently. stackoverflow.com/questions/11127908/… Commented Nov 25, 2019 at 8:55

8 Answers 8

150

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

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

Sign up to request clarification or add additional context in comments.

4 Comments

document.getElementById('gift-close').onClick(); doesn't work in Chrome, Firefox, or Safari. However, changing onClick() to click() does work.
Didn't the asker explicity say that this doesn't work? I don't understand the upvotes.
@HugoZink because it does work..? Did you try anything before downvoting/commenting?
@AndréDion I did, and it does not seem to work in Firefox. Probably due to security concerns.
21

Using jQuery:

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

9 Comments

Why would that work when document.getElementById("gift-close").click(); didn't?
Because document.getElementById("gift-close") is not a jQuery object but a DOM object. You could try this too: $(document.getElementById("gift-close")).click();
@techfoobar and Alex, DOM elements have a .click() method. jsfiddle.net/LKNYg
@nnnnnn - Wow! Totally new info for me.. Never knew that.. Tks :-)
Oh, yes. You're right. Then the problem is that he should execute click code after page loading, i.e. in onReady event ;)
|
17

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);      
}

3 Comments

Also look at this question stackoverflow.com/questions/15951468/… this describes newer approach to creating custom events.
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);
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.
10

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>

Comments

9

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();
});

3 Comments

I want to make the inline onclick handler execute
Right. And that happens in both of the jsfiddle demos I provided.
The trick I found (compared to the "best" answer) was to use the [0]. That caused the script to work.
2

Use this code to click:

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

2 Comments

Why would that work when document.getElementById("gift-close").click(); didn't?
You have to run your code from onload handler for javascript, or $(document).ready(function(){//write code here}) for JQuery
-3

Here, try this one:

$('#gift-close').on('click', function () {
    _gaq.push(['_trackEvent','voucher_new','cart',$(this).attr('rel')+'-mask_x_button-inaction']);
});

Comments

-3

Try adding a function inside the click() method.

$('#gift-close').click(function(){
  //do something here
});

It worked for me with a function assigned inside the click() method rather than keeping it empty.

1 Comment

this is a click event listener, not a click event trigger

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.