I'm having a hard time understand how to simulate a mouse click using JQuery. Can someone please inform me as to 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
when I click on button #foo I want to simulate a click on #bar however when I attempt this, nothing happens. I also tried jQuery(document).ready(function(){...})
but without success.
The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
Answer: Use the jQuery click() Method You can use the click() method to trigger a click on a link programmatically using jQuery.
If you want native JS to trigger click event without clicking then use the element id and click() method of JavaScript.
So Why Does It Happen? JQuery OnClick Method is bound to an element or selector on page ready/load. Therefore if that element you want to click isn't there at the time of page ready, the binding can't happen.
You need to use jQuery('#bar')[0].click();
to simulate a mouse click on the actual DOM element (not the jQuery object), instead of using the .trigger()
jQuery method.
Note: DOM Level 2 .click()
doesn't work on some elements in Safari. You will need to use a workaround.
http://api.jquery.com/click/
You just need to put a small timeout event before doing .click()
like this :
setTimeout(function(){ $('#btn').click()}, 100);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With