77

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

user2373137
  • 806
  • 1
  • 8
  • 10

8 Answers8

120

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

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

André Dion
  • 19,231
  • 7
  • 52
  • 59
  • 4
    `document.getElementById('gift-close').onClick();` doesn't work in Chrome, Firefox, or Safari. However, changing `onClick()` to `click()` does work. – 425nesp Aug 13 '14 at 01:38
  • 7
    Didn't the asker explicity say that this *doesn't* work? I don't understand the upvotes. – Hugo Zink Jul 01 '16 at 11:34
  • @HugoZink because it **does** work..? Did you try anything before downvoting/commenting? – André Dion Jul 04 '16 at 11:25
  • 1
    @AndréDion I did, and it does not seem to work in Firefox. Probably due to security concerns. – Hugo Zink Jul 06 '16 at 16:06
20

Using jQuery:

$('#gift-close').click();
Alex Guerra
  • 302
  • 1
  • 6
  • 3
    Why would that work when `document.getElementById("gift-close").click();` didn't? – nnnnnn Jul 10 '13 at 11:06
  • Because document.getElementById("gift-close") is not a jQuery object but a DOM object. You could try this too: $(document.getElementById("gift-close")).click(); – Alex Guerra Jul 10 '13 at 11:08
  • 3
    @techfoobar and Alex, DOM elements have a `.click()` method. http://jsfiddle.net/LKNYg/ – nnnnnn Jul 10 '13 at 11:09
  • @nnnnnn - Wow! Totally new info for me.. Never knew that.. Tks :-) – techfoobar Jul 10 '13 at 11:09
  • Oh, yes. You're right. Then the problem is that he should execute click code after page loading, i.e. in onReady event ;) – Alex Guerra Jul 10 '13 at 11:13
  • @roasted - It did fire the inline `onclick` for me in Chrome: http://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). – nnnnnn Jul 10 '13 at 11:19
  • @nnnnnn you are right! Just the native behaviour of anchor tag is not fired, my bad! – A. Wolff Jul 10 '13 at 11:21
  • I want to make the inline onclick handler execute – user2373137 Jul 10 '13 at 11:26
15

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);      
}
ihor marusyk
  • 600
  • 3
  • 12
  • 1
    Also look at this question http://stackoverflow.com/questions/15951468/what-is-a-good-example-of-using-event-constructors-in-js this describes newer approach to creating custom events. – ihor marusyk Jul 10 '13 at 14:35
  • 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); – Humayun Mar 17 '17 at 12:56
  • 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. – Ellert van Koperen Oct 02 '17 at 11:40
9

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>
ravo10
  • 747
  • 7
  • 17
8

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();
});
nnnnnn
  • 138,378
  • 23
  • 180
  • 229
2

Use this code to click:

$("#gift-close").click();
Farid Imranov
  • 1,729
  • 15
  • 28
  • 1
    Why would that work when `document.getElementById("gift-close").click();` didn't? – nnnnnn Jul 10 '13 at 11:11
  • You have to run your code from `onload` handler for javascript, or `$(document).ready(function(){//write code here})` for JQuery – Farid Imranov Jul 11 '13 at 05:34
0

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.

Neo
  • 712
  • 1
  • 7
  • 21
-3

Here, try this one:

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