I installed an event handler on an input
using
var element = document.getElementById('some-input'); element.addEventListener('input', function() { console.log('The value is now ' + element.value); });
As expected, the handler is triggered when I type into the text field, but I also need to invoke this handler from my code. How can I simulate the input
event so that my event listener is called?
Use the dispatchEvent Method querySelector('input'); element. addEventListener('change', () => console. log('change')) const event = new Event('change'); element. dispatchEvent(event);
Like an Apex trigger for Salesforce objects, you define a change event trigger on the change event corresponding to the Salesforce object. Only after insert triggers are supported. Define a change event trigger with the after insert keyword on the change event using this format.
The proper way to trigger an event with plain JavaScript, would be to create an Event object, and dispatch it
var event = new Event('input', { bubbles: true, cancelable: true, }); element.dispatchEvent(event);
Or, as a simple one-liner:
element.dispatchEvent(new Event('input', {bubbles:true}));
FIDDLE
This is not supported in IE, for that the old-fashioned way still has to be used
var event = document.createEvent('Event'); event.initEvent('input', true, true); elem.dispatchEvent(event);
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