Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 949
lickmycode Avatar asked Sep 26 '22 15:09

lickmycode


People also ask

How do you trigger a click element?

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.

How do you trigger a click event for a hyperlink?

Answer: Use the jQuery click() Method You can use the click() method to trigger a click on a link programmatically using jQuery.

How do I trigger a click event without clicking?

If you want native JS to trigger click event without clicking then use the element id and click() method of JavaScript.

Why jQuery click function is not working?

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.


2 Answers

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/

like image 303
Alex W Avatar answered Oct 13 '22 15:10

Alex W


You just need to put a small timeout event before doing .click() like this :

setTimeout(function(){ $('#btn').click()}, 100);
like image 56
Ashish Khurana Avatar answered Oct 13 '22 15:10

Ashish Khurana