Simulate a click on 'a' element using javascript/jquery
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
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:
- Run your code from an
onload
handler for the window. http://jsfiddle.net/LKNYg/ - Run your code from a document ready handler if you're using jQuery. http://jsfiddle.net/LKNYg/1/
- 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();
});
Related videos on Youtube
user2373137
Updated on July 08, 2022Comments
-
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"> </a>
How can i simulate a click on it. I have tried
document.getElementById("gift-close").click();
But its not doing anything
-
nnnnnn almost 11 yearsWhere 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 almost 11 yearsIf 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 almost 11 yearsI want to make the inline onclick handler execute
-
AmerllicA about 7 yearsPlease, just please do not write
href="javascript:void(0)"
. It has critical SEO issues. -
Sunil Kumar over 4 yearsPlease note that user-click and triggered programmed click work differently. stackoverflow.com/questions/11127908/…
-
-
nnnnnn almost 11 yearsWhy would that work when
document.getElementById("gift-close").click();
didn't? -
Alex Guerra almost 11 yearsBecause document.getElementById("gift-close") is not a jQuery object but a DOM object. You could try this too: $(document.getElementById("gift-close")).click();
-
nnnnnn almost 11 years@techfoobar and Alex, DOM elements have a
.click()
method. jsfiddle.net/LKNYg -
techfoobar almost 11 years@nnnnnn - Wow! Totally new info for me.. Never knew that.. Tks :-)
-
nnnnnn almost 11 yearsWhy would that work when
document.getElementById("gift-close").click();
didn't? -
Alex Guerra almost 11 yearsOh, yes. You're right. Then the problem is that he should execute click code after page loading, i.e. in onReady event ;)
-
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 anhref
containing a URL). -
A. Wolff almost 11 years@nnnnnn you are right! Just the native behaviour of anchor tag is not fired, my bad!
-
user2373137 almost 11 yearsI want to make the inline onclick handler execute
-
user2373137 almost 11 yearsI want to make the inline onclick handler execute
-
nnnnnn almost 11 yearsRight. And that happens in both of the jsfiddle demos I provided.
-
ihor marusyk almost 11 yearsAlso look at this question stackoverflow.com/questions/15951468/… this describes newer approach to creating custom events.
-
Farid Imranov almost 11 yearsYou have to run your code from
onload
handler for javascript, or$(document).ready(function(){//write code here})
for JQuery -
425nesp almost 10 years
document.getElementById('gift-close').onClick();
doesn't work in Chrome, Firefox, or Safari. However, changingonClick()
toclick()
does work. -
Hugo Zink almost 8 yearsDidn't the asker explicity say that this doesn't work? I don't understand the upvotes.
-
André Dion almost 8 years@HugoZink because it does work..? Did you try anything before downvoting/commenting?
-
Hugo Zink almost 8 years@AndréDion I did, and it does not seem to work in Firefox. Probably due to security concerns.
-
Humayun about 7 yearsWow 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 over 6 yearsChange "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 over 3 yearsThe trick I found (compared to the "best" answer) was to use the [0]. That caused the script to work.
-
Aditya over 2 yearsShouldn't Be used any more because of Jquery 3.6.0 it's outdated.
-
Tudor about 2 yearsthis is a click event listener, not a click event trigger