Problem
I’m having trouble understanding how to utilize JQuery to simulate a mouse click. Could someone kindly tell me what I’m doing wrong?
HTML:
<a id="bar" href="http://stackoverflow.com" target="_blank">Don't click me!</a>
<span id="foo">Click me!</span>
jQuery:
jQuery('#foo').on('click', function(){
jQuery('#bar').trigger('click');
});
Demo: FIDDLE
I want to simulate a click on #bar when I click button #foo, but nothing happens when I try. I also experimented with jQuery (document). ready(function()…), but to no avail.
Asked by lickmycode
Solution #1
jQuery(‘#bar’)[0] is required. Instead of utilizing the.trigger() jQuery method, use click() to simulate a mouse click on the actual DOM element (not the jQuery object).
In Safari, DOM Level 2.click() does not work on some items. You’ll have to devise a workaround.
http://api.jquery.com/click/
Answered by Alex W
Solution #2
All you have to do now is add a brief timeout event before doing. like this: click()
setTimeout(function(){ $('#btn').click()}, 100);
Answered by Ashish Khurana
Solution #3
This is how JQuery works. I’m not sure why it works this way; it simply activates the link’s onClick function.
Try:
jQuery(document).ready(function() {
jQuery('#foo').on('click', function() {
jQuery('#bar')[0].click();
});
});
Answered by Filip Górny
Solution #4
See http://jsfiddle.net/8AVau/1/ for an example.
jQuery(document).ready(function(){
jQuery('#foo').on('click', function(){
jQuery('#bar').simulateClick('click');
});
});
jQuery.fn.simulateClick = function() {
return this.each(function() {
if('createEvent' in document) {
var doc = this.ownerDocument,
evt = doc.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, doc.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
} else {
this.click(); // IE Boss!
}
});
}
Answered by Reza Mamun
Solution #5
May be useful:
After the event has been called, the code that calls the Trigger should be executed.
For example, I have some code that I want to run when the value of #expense tickets changes, as well as when the page is reloaded.
$(function() {
$("#expense_tickets").change(function() {
// code that I want to be executed when #expense_tickets value is changed, and also, when page is reload
});
// now we trigger the change event
$("#expense_tickets").trigger("change");
})
Answered by Albert Català
Post is based on https://stackoverflow.com/questions/20928915/how-to-get-jquery-triggerclick-to-initiate-a-mouse-click