Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain addEventListener?

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

like image 925
JoeTidee Avatar asked Dec 11 '22 11:12

JoeTidee


1 Answers

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.

like image 121
idmean Avatar answered Jan 07 '23 10:01

idmean