In this article we will see how to bind multiple events to elements with JavaScript.
We can create a function that associates events with an element using three arrays: one for the type of events, one for the event handlers, and one for the event's capture. We can implement the following solution.
'use strict';
const addEventListeners = (element = null, types = [], listener = [], useCapture = []) => {
if(element === null || !element) {
return false;
}
if(types.length === 0 || listener.length === 0 || useCapture.length === 0) {
return false;
}
const length = types.length;
if(listener.length !== length || useCapture.length !== length) {
return false;
}
types.forEach((type, index) => {
let evtListener = listener[index];
let capture = useCapture[index];
if(typeof evtListener === 'function' && typeof capture === 'boolean') {
element.addEventListener(type, evtListener, capture);
}
});
};
Usage example:
const inputEl = document.getElementById('email');
const onFocus = function() {
inputEl.classList.add('focused');
};
const onBlur = function() {
inputEl.classList.remove('focused');
};
addEventListeners(inputEl, ['focus', 'blur'], [onFocus, onBlur], [false, false]);