james emanon
james emanon

Reputation: 11807

Any way to know if the click is coming from a "trigger" or actual click?

I have a curious situation. I am editing a page that is a gazzilion moving parts.

Anyways, I have a dialog box (popup) that is bound (via the dialog creation class) to a body click handler. Basically, if you click anywhere on the page, it closes. Ok, great.

Here is the rub. There is another process on the page that runs that "$(body).trigger('click')". This is creating an issue, because in THIS situation, I do not want my particular dialog to close.

I ran some tests and they appear to be identical -- 1.) generating a click via a trigger 2.) and actually clicking on the body of the page.

Is there any discernible way to know if a click is a "fake" trigger call or real 'click' event? Since nothing is bubbling in a triggered click, is there anyways to somehow try to see if there is a child elem on the page to see if its bubbling or something?

I hope I am succinct enough in my explanation.

Upvotes: 1

Views: 123

Answers (1)

Krasimir
Krasimir

Reputation: 13529

HTML:

<input type="button" id="button" value="click me" />

JS:

$("#button").on("click", function(e) {
    if(typeof e.isTrigger == 'undefined') {
        console.log("clicked");
    } else {
        console.log("triggered");
    }
});

setTimeout(function() {
    $("#button").trigger("click");
}, 1000);

Demo: http://jsfiddle.net/wXnwp/1/

A version for jQuery 1.6 => http://jsfiddle.net/wXnwp/3/

$("#button").click(function(e) {
    if(typeof e.ctrlKey !== 'undefined') {
        console.log("clicked");
    } else {
        console.log("triggered");
    }
});

setTimeout(function() {
    $("#button").trigger("click");
}, 1000);

Upvotes: 3

Related Questions