Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - detect change event triggered programmatically

I have a jQuery change event for when a user changes a given SELECT element. However the event may also be triggered by a third party script. What I want to do is detect whether the event was triggered programmatically or by the user.

I have tried the accepted solution in this question Check if event is triggered by a human But note the JSFiddle in this answer is for a click event rather than a change event.

To demonstrate I amended the fiddle and created this one: http://jsfiddle.net/Uf8Wv/231/

If you try this in latest Firefox or Chrome, you will see that the alert human is being shown even when the event was triggered programmatically.

I have tried event.originalEvent.isTrusted but that doesn't work in all browsers. Can anyone help?

like image 229
MAX POWER Avatar asked Oct 31 '22 01:10

MAX POWER


2 Answers

I have added mouseenter and mouseleave events. The idea is that it's a human if the click coincided with a mousepointer being over the element. See: http://jsfiddle.net/Uf8Wv/232/

$("#try").mouseenter(function(event) {
    mouseover = true;
});
// ... etc.

I can't think of any other way.

like image 160
brandon Avatar answered Nov 12 '22 17:11

brandon


You can find some vague difference between click and emulated click using this code:

$(document).on('change', "#try", function (event) {
    //some difference appear in the next line
    console.log(event.delegateTarget.activeElement);
    //no difference
    if (event.originalEvent === undefined) {
        alert('not human')
    } else {
        alert(' human');
    }
    event.delegateTarget = null;//doesn't help

});

$('#click').click(function (event) {
    $("#try").click();
});

Click on the checkbox logs <input id="try" type="checkbox">.
Click on the button logs <button id="click">.
But...
Run $("#try").click(); from console before any clicks logs <body> and after the click result of the last click.
Generally JS can always fake any client event. So isTrusted is never trusted.

like image 31
Alex Kudryashev Avatar answered Nov 12 '22 16:11

Alex Kudryashev