I have the following code:
document.querySelector('.mySelector').addEventListener("mouseover", function() {
this.parentNode.parentNode.classList.add("over");
});
document.querySelector('.mySelector').addEventListener("mouseout", function(){
this.parentNode.parentNode.classList.remove("over");
});
Given that the two events are on the same target, is there a way to chain the two addEventListener
methods similar to this? :
document.querySelector('.mySelector').addEventListener("mouseover", function() {
this.parentNode.parentNode.classList.add("over");
}).addEventListener("mouseout", function(){
this.parentNode.parentNode.classList.remove("over");
});
Doing this produces an error:
Uncaught TypeError: Cannot read property 'addEventListener' of undefined
Chaining addEventListener
is not possible as the method does not return anything (it actually does return undefined
). The specification specifies it as:
interface EventTarget { void addEventListener(in DOMString type, in EventListener listener, in boolean useCapture);
You can, of course, replace addEventListener
with your own implementation:
EventTarget.prototype.addEventListener = (() => {
const addEventListener = EventTarget.prototype.addEventListener;
return function() {
addEventListener.apply(this, arguments);
return this;
};
})();
document.querySelector('button').addEventListener('hover', () => {
console.log('hover');
}).addEventListener('click', () => {
console.log('click');
});
But messing about with built-in prototypes is something that is often advised against, as it can have unwanted side effects.
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