I am using a datalist and need to detect when the user selects something from the drop-down list. A similar question has been asked BUT I need it so that the event fires ONLY wh
This might only be Chrome, untested anywhere else!, but I see a change
event triggered when an option is selected. Normally change
only happens in textfields when the field loses focus. The change
event triggers before the blur
event IF it's a normal non-datalist change, so we have to check both: we're looking for a change
that's not immediately followed by a blur
:
var timer;
el.addEventListener('change', function(e) {
timer = setTimeout(function() {
el.dispatchEvent(new CustomEvent('datalistchange'));
}, 1);
});
el.addEventListener('blur', function(e) {
clearTimeout(timer);
});
And then you can listen for the custom datalistchange
event like normally. Or you can just put your specific logic instead of the dispatchEvent
.
jsFiddle here