Is there a way to find out if an event handler was fired with code in jQuery without custom flags?

Consider this jQuery code ...

$('button#my').click(function(event) {
    alert('hello');
});

$('button#my').click();

Obviously, this will bring up a warning window.

However, can I only say with jQuery if this event handler was launched with the code or if the user clicked it (without checking the ugly flag, for example var userClicked = true).

I thought there would be a property event, but I could not figure it out.

Is it possible?

Thank.

+3
source share
3 answers

You can check if event.whichthis will be undefinedfor .click()(or other triggers) ... for example:

$('button#my').click(function(event) {
    if(event.which) {
        alert("User click");
    } else {
        alert("triggered click");
    }
});

Here you can try here .

+7

, ; Firebug $("button#my").click(console.log), , click(). - event.currentTarget, , document, click() ed ( , , ). - (offset|client|layer)[XY] , click() ..

(Edit: , event.which - : 1 click().)

+1

. , .

.click() , .trigger('click') .click().

: http://jsfiddle.net/patrick_dw/jWFAn/

// Passed via .trigger() ----------------v
$('button#my').click(function(event, wasManual) {
    if( wasManual ) {
        alert('triggered in code');
    } else {
        alert('triggered by mouse');
    }
});

  // Array of additional args------v
$('button#my').trigger( 'click', [true] );

Thus, it uses the explicit jQuery function in a supported form.

+1
source

Source: https://habr.com/ru/post/1776814/


All Articles