Coder Perfect

To initiate a mouse click, use JQuery.trigger(‘click’);


I’m having trouble understanding how to utilize JQuery to simulate a mouse click. Could someone kindly tell me what I’m doing wrong?


<a id="bar" href="" target="_blank">Don't click me!</a>
<span id="foo">Click me!</span>


jQuery('#foo').on('click', function(){


I want to simulate a click on #bar when I click button #foo, but nothing happens when I try. I also experimented with jQuery (document). ready(function()…), but to no avail.

Asked by lickmycode

Solution #1

jQuery(‘#bar’)[0] is required. Instead of utilizing the.trigger() jQuery method, use click() to simulate a mouse click on the actual DOM element (not the jQuery object).

In Safari, DOM Level does not work on some items. You’ll have to devise a workaround.

Answered by Alex W

Solution #2

All you have to do now is add a brief timeout event before doing. like this: click()

setTimeout(function(){ $('#btn').click()}, 100);

Answered by Ashish Khurana

Solution #3

This is how JQuery works. I’m not sure why it works this way; it simply activates the link’s onClick function.


jQuery(document).ready(function() {
    jQuery('#foo').on('click', function() {

Answered by Filip Górny

Solution #4

See for an example.

    jQuery('#foo').on('click', function(){

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);
        } else {
  ; // IE Boss!

Answered by Reza Mamun

Solution #5

May be useful:

After the event has been called, the code that calls the Trigger should be executed.

For example, I have some code that I want to run when the value of #expense tickets changes, as well as when the page is reloaded.

$(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


Answered by Albert Català

Post is based on