we can detect if a user changes something:
$('#item').change(function() {
alert('changed!');
});
sadly, sometimes I need to call it artiffically: $('#item').change()
but in this case it is also taken as "changed". Is there a way to distinguish user actvity from manual activity?
The first argument returned from a jQuery event handler is the event object:
$('#item').change(function(e) {
console.log(e); // The event object
});
The way I usually differentiate between a user-triggered event and a code-triggered event is that user-triggered events have an originalEvent
property attached to them. I don't know if this is the best approach, but I'd do it like this:
$('#item').change(function(e) {
if (e.originalEvent) {
// user-triggered event
}
else {
// code-triggered event
}
});
Type in the input
element in the below example, then unfocus the element. You'll get an alert saying "user-triggered"
. Click the button to call a code-triggered change. You'll get an alert saying "code-triggered"
.
$('#item').change(function(e) { if (e.originalEvent) { alert('user-triggered') } else { alert('code-triggered') } }); $('button').on('click', function() { $('#item').change(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type=text id=item /> <button>Click here to trigger change</button>
A different approach from originalEvent
should be using event params:
$('#item').change(function(event, who) {
if(who === "machine")
alert('machine!');
else
alert('human!');
});
$("#item").trigger("change", ["machine"]);
The event parameter of the callback will contain an originalEvent key when a the event is triggered by the user, so you can do:
$('#item').change(function(e){ if (e.originalEvent){ alert('Changed by user'); } // Place common code here });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.