Trigger an Event

Some elements provide specific methods for triggering an event.

For example, to trigger a click event on any element, you use the click() method:

el.click();Code language: CSS (css)

The input text and text area elements provide the focus() and blur() methods for triggering the focus and blur events:

el.focus();
el.blur();Code language: CSS (css)

The form element has the submit() and reset() methods for triggering the submit and reset events:

const frm = document.querySelector('form');
// trigger the submit event
frm.submit();

// trigger the reset event
frm.reset();
Code language: JavaScript (javascript)

To trigger other events such as the mousedown or change, you use the following triggerEvent() helper function:

function triggerEvent(el, type) {
    // IE9+ and other modern browsers
    if ('createEvent' in document) {
        var e = document.createEvent('HTMLEvents');
        e.initEvent(type, false, true);
        el.dispatchEvent(e);
    } else {
        // IE8
        var e = document.createEventObject();
        e.eventType = type;
        el.fireEvent('on' + e.eventType, e);
    }
}Code language: JavaScript (javascript)

Suppose that you have an input text:

<input type="text" name="username">Code language: HTML, XML (xml)

The following binds an event handler to the click event:

const input = document.querySelector('input[type="text"]');
input.addEventListener('change', (e) => {
    console.log('Input changed');
});Code language: JavaScript (javascript)

To trigger the change event, you use the triggerEvent() function as follows:

triggerEvent(input, 'change');Code language: JavaScript (javascript)
Was this tutorial helpful ?