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?
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?
3 Answers
Reset to default 47The 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
}
});
Example
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 });
$( "#item" ).keypress(function() { alert('changed!'); });
For clicky inputs, you can use click handlers: If it's a text input, you can use the Keypress function, as follows:$( "#item" ).on("click", function() { alert('changed!'); });
– Niek Commented Feb 24, 2016 at 9:30keypress
event will not fire if you paste things in (either via keyboard or mouse). – James Donnelly Commented Feb 24, 2016 at 9:47