Erdinç Özdemir
Erdinç Özdemir

Reputation: 1381

Check html element's click event fired programmatically or by clicking with mouse

I must check which is fired the click event, click with mouse or .click() function. Is it possible?

Upvotes: 0

Views: 231

Answers (2)

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

Yes, you can do that like this...

$('button').on("click", function(e){
    if (e.originalEvent !== undefined) {
        // the button was actually clicked
    } else {
        // the button was triggered by code
    }
});

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074258

You can tell by looking at the pageX or pageY property of the event object, which will be undefined if $("some selector").click(); was used, but a number if an actual mouse click occurred. For example:

(function($) {

  $("#target").click(function(e) {
    if (typeof e.pageX === "undefined") {
      display("Fired programatically");
    }
    else {
      display("Fired by real click");
    }
  });

  setTimeout(function() {
    $("#target").click();
  }, 500);

  function display(msg) {
    $("<p>").html(String(msg)).appendTo(document.body);
  }

})(jQuery);

Live Copy | Source

Of course, if someone gets really clever and builds a full click event including fake pageX and pageY information, that won't work, but jQuery's default handling of $("some selector").click(); doesn't do that.

Upvotes: 1

Related Questions