lickmycode lickmycode - 4 months ago 17
HTML Question

jQuery.trigger('click') not working

It seems that I just can not understand the jQuery trigger('click') function correctly.

Can someone please tell me why this simple code doesn't work and how to fix?

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

What I want is to be able to click on #foo (which is working well) and simulating a click on #bar (which is completly ignored without any error messages).
Tried also with the
jQuery(document).ready(function(){...})
but without success.

Answer

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/