skip to Main Content

I am trying to define some hover properties using JavaScript. So, I decided to go with "mouseenter" and "mouseleave" events for an element. Now, I have to call the same function for both the events in addEventListener.

So, is there any way of doing it like:

element.addEventListener("mouseenter" or "mouseleave", myfunc);

3

Answers


  1. Well you cannot use an "or" to add multiple listeners but you can create one function and add multiple listeners to it. Here is an example:

    function myfunc() { 
      console.log("Event is called");
    }
    
    element.addEventListener("mouseenter", myfunc);
    element.addEventListener("mouseleave", myfunc);
    
    Login or Signup to reply.
  2. Well if you need both events, then you should add two event listeners, so the syntax should look like this.

    element.addEventListener("mouseenter", func);
    element.addEventListener("mouseleave", func);
    

    or

    ["mouseenter", "mouseleave"].forEach(event => {
      element.addEventListener(event, func);
    })
    

    It’s the same thing

    Login or Signup to reply.
  3. For this exact syntax you should override the addEventListener:

    {
      let _add;
      [_add, HTMLElement.prototype.addEventListener] = [HTMLElement.prototype.addEventListener, function(name, ...args){
        name.match(/S+/g).forEach(name => _add.call(this, name, ...args));  
      }];
    }
    
    $test.addEventListener('mouseenter mouseleave', e => console.log(e.type));
    [id=$test]{
      width:200px;
      height:150px;
      background:gray;
    }
    <div id="$test"></div>

    An one-liner without overriding:

    'mouseenter mouseleave'.split(' ').forEach(name => $test.addEventListener(name, e => console.log(e.type)));
    [id=$test]{
      width:200px;
      height:150px;
      background:gray;
    }
    <div id="$test"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search