Reputation: 139
Is it possible to determine if an event such as input
, blur
, change
etc. was fired due to a user interaction or if it was fired programmatically using inputElement.dispatchEvent(new Event('change'))
etc.?
The problem I am facing is that a third-party UI library registered an event handler that listens for blur
and changes the appearance of an input element if it's empty. I have an own blur
handler that blanks the input if certain criteria is met. Since my event handler is executed after the library's, the library doesn't notice that the input is now empty and re-throwing the blur event would cause an endless loop.
Or is it safe to add custom properties to events, something like...
document.getElementById('input').addEventListener('blur', event => {
if (event.myOwnCustomProperty !== true) {
event.target.value = ''
const customEvent = new Event('blur')
customEvent.myOwnCustomProperty = true
event.target.dispatchEvent(customEvent)
}
})
<input id="input">
Upvotes: 1
Views: 1258
Reputation: 6180
You can use the isTrusted
property of the event to check whether it was triggered by user interaction or not:
The
isTrusted
read-only property of theEvent
interface is aBoolean
that istrue
when the event was generated by a user action, andfalse
when the event was created or modified by a script or dispatched viaEventTarget.dispatchEvent()
.
document.getElementById('input').addEventListener('blur', event => {
if (event.isTrusted) {
...
}
})
Note that the user can still fire events from the debugger, either manually or programatically, and in this case you will never know where the event originated from.
Upvotes: 5