Search code examples
javascriptfunctionevent-handlingdom-eventsbind

How can I pass the DOM event as an event handler bind method


nav.addEventListener('mouseover',handleHover.bind(null,e,0.5))

I want to passing event itself as an argument to bind method but it gives an error. e is undefined. How can I pass the event itself into an event handler bind method?


Solution

  • You can pass arguments:

    const handleHover = (event, opacity) => { 
      event.target.style.opacity = opacity; 
    }
    
    nav.addEventListener('mouseover', () => handleHover(event, 0.5));
    <div id="nav">Mouse Over</div>

    Using bind (Not Recommended, just for clarification):

    const handleHover = () => { 
      event.target.style.opacity = opacity; 
    }
    
    nav.addEventListener('mouseover', handleHover.bind(event, opacity=0.5));
    <div id="nav">Mouse Over</div>