How to get JQuery.trigger('click'); to initiate a mouse click

lickmycode picture lickmycode · Jan 5, 2014 · Viewed 229.8k times · Source

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.

Answer

Alex W picture Alex W · Jan 5, 2014

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/