162

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.

Patrick W. McMahon
  • 3,488
  • 1
  • 20
  • 31
lickmycode
  • 2,069
  • 2
  • 19
  • 20
  • 3
    `jQuery trigger` only works if any 'jQuery click` event is added. Otherwise you will not be able to do anything by this way; – Reza Mamun Jan 05 '14 at 01:26
  • 3
    This is a security measure built into the browser. See @Blazemonger's answer: http://stackoverflow.com/questions/7999806/jquery-how-to-trigger-click-event-on-href-element – sanchez Jan 05 '14 at 01:26
  • 1
    @san.chez Interesting, thanks for the info, didn't knew about this security measure before! – lickmycode Jan 05 '14 at 01:40

11 Answers11

307

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/

Community
  • 1
  • 1
Alex W
  • 37,233
  • 13
  • 109
  • 109
59

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

setTimeout(function(){ $('#btn').click()}, 100);
noufalcep
  • 3,446
  • 15
  • 33
  • 51
Ashish Khurana
  • 691
  • 5
  • 3
  • Works perfect if you are trying to simulate a click when the page loads. – Gabriel Dzul Apr 12 '19 at 05:35
  • 2
    This solved my problem too, thanks. None of the other solutions worked reliably. My code showed a modal, then simulated a click on a tab. Why is the delay necessary? I had to use 500ms to be on safe side. – Henry Jan 01 '21 at 11:34
  • Brilliant! This solved my issue. Why is timeout required? Nothing else worked for me. – cosmoonot Aug 22 '23 at 03:45
36

This is JQuery behavior. I'm not sure why it works this way, it only triggers the onClick function on the link.

Try:

jQuery(document).ready(function() {
    jQuery('#foo').on('click', function() {
        jQuery('#bar')[0].click();
    });
});
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
Filip Górny
  • 1,749
  • 16
  • 24
  • Not irritating at all. `trigger()` is intended to execute the click event **JavaScript** portion. It's very similar to creating a `function var() {}` thats re-used multiple times. –  Mar 11 '17 at 15:33
24

See my demo: http://jsfiddle.net/8AVau/1/

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!
        }
    });
}
Reza Mamun
  • 5,991
  • 1
  • 43
  • 42
  • I would wrap the `this.click();` in an `else if(this.click)` – Alex W Nov 20 '15 at 15:55
  • Why are you passing the string `'click'` into the `simulateClick` function? It doesn't seem to be used. – clayRay Jun 29 '21 at 03:20
  • @clayRay - yes, I agreed with you. It was made many years ago keeping in mind to make dynamic based on params. But later on I have just tried to make the solution of current requirement. Thanks for your observation. – Reza Mamun Jun 29 '21 at 10:30
15

May be useful:

The code that calls the Trigger should go after the event is called.

For example, I have some code that I want to be executed when #expense_tickets value is changed, and also, when page is reload

$(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");

})
davewasthere
  • 2,988
  • 2
  • 24
  • 25
Albert Català
  • 2,026
  • 2
  • 29
  • 35
  • 4
    Ahhh that was my problem too! Was baffled as to why the `trigger()` wasn't working. Turns out I had the trigger code set ABOVE the function it was calling - so the hook wasn't actually in place. Doh! – Andrew Newby Dec 10 '16 at 12:10
5

jQuery's .trigger('click'); will only cause an event to trigger on this event, it will not trigger the default browser action as well.

You can simulate the same functionality with the following JavaScript:

jQuery('#foo').on('click', function(){
    var bar = jQuery('#bar');
    var href = bar.attr('href');
    if(bar.attr("target") === "_blank")
    {
        window.open(href);
    }else{
        window.location = href;
    }
});
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
3

Try this that works for me:

$('#bar').mousedown();
Henry
  • 1,077
  • 1
  • 16
  • 41
1

Technically not an answer to this, but a good use of the accepted answer (https://stackoverflow.com/a/20928975/82028) to create next and prev buttons for the tabs on jQuery ACF fields:

$('.next').click(function () {
    $('#primary li.active').next().find('.acf-tab-button')[0].click();
});

$('.prev').click(function () {
    $('#primary li.active').prev().find('.acf-tab-button')[0].click();
});
Tisch
  • 2,598
  • 4
  • 27
  • 34
0

I have tried top two answers, it doesn't worked for me until I removed "display:none" from my file input elements. Then I reverted back to .trigger() it also worked at safari for windows.

So conclusion, Don't use display:none; to hide your file input , you may use opacity:0 instead.

Himanshu Saini
  • 702
  • 11
  • 25
-1

Just use this:

$(function() {
 $('#watchButton').trigger('click');
});
Sanath L S
  • 1,309
  • 8
  • 10
-3

You can't simulate a click event with javascript. jQuery .trigger() function only fires an event named "click" on the element, which you can capture with .on() jQuery method.

yachaka
  • 5,429
  • 1
  • 23
  • 35
  • 9
    _"You can't simulate a click event with javascript"_ - [Yes you can](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.click). – nnnnnn Jan 05 '14 at 02:06
  • Wrong... you can simulate a click event with javascript/jquery and you can capture trigger click event with .click without on. – Aerious Oct 12 '15 at 13:03