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?
Definition and Usage The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus, after the content has been changed.
When you dynamically set a value in a textfield using jQuery . val(), you have to manually trigger the . change event if you want to add extra code that trigger when the value of the field change.
The change() method triggers the change event, or attaches a function to run when a change event occurs. Note: For select menus, the change event occurs when an option is selected. For text fields or text areas, the change event occurs when the field loses focus, after the content has been changed.
jQuery trigger() Method The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.
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"]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With