How to programmatically trigger an "input" event without jQuery?

I set the event handler to input using

 var element = document.getElementById('some-input'); element.addEventListener('input', function() { console.log('The value is now ' + element.value); }); 

As expected, the handler starts when text is entered into the text box, but I also need to call this handler from my code. How can I simulate an input event to trigger my event listener?

+7
javascript
source share
1 answer

The proper way to trigger an event using regular JavaScript is to create an Event object and send it

 var event = new Event('input', { 'bubbles': true, 'cancelable': true }); element.dispatchEvent(event); 

Fiddle

This is not supported in IE, as you need to use the old-fashioned way.

 var event = document.createEvent('Event'); event.initEvent('input', true, true); elem.dispatchEvent(event); 
+21
source share

All Articles