2

Right now, I'm using jQuery to find elements and attach event listeners. I don't want to use jQuery anymore.

this.$('.my-class').off().on({
   mouseenter : this.handleMouseOverEvent.bind(this),
   mouseleave : this.handelMouseLeaveEvent.bind(this),
   click : this.handelMouseLeaveEvent.bind(this),
}); 

How can I attach event-listeners just with plain Javascript?

Codekie
  • 7,574
  • 3
  • 18
  • 26
Mari Selvan
  • 3,598
  • 3
  • 21
  • 36

1 Answers1

1

Use querySelectorAll to select elements and addEventListener to bind listeners to the events.

Event-listeners can be removed with removeEventListener. However, you'll have to remove the listeners manually. Javascript does not track them for you, as jQuery's off does.

Here, the browser support for:

document.querySelectorAll('.my-class')
  .forEach(element => {
    element.addEventListener('mouseover', () => element.style.backgroundColor = 'green');
    element.addEventListener('mouseout', () => element.style.backgroundColor = 'transparent');
  });
<!doctype html>
<html>
  <head>
    <title>Bind event handlers</title>
  </head>
  <body>
    <ul>
      <li class="my-class">hover me</li>
      <li class="my-class">hover me</li>
    </ul>
  </body>
</html>
Codekie
  • 7,574
  • 3
  • 18
  • 26
  • But what about the `off()`. I mean remove event listener. And if you use () => {} an anonymous functional declaration this wont work right. – Mari Selvan Jul 09 '19 at 14:36
  • I have updated my answer – Codekie Jul 09 '19 at 14:41
  • 1
    @MariSelvan No, anonymous functions won't work. You'll need a reference to the original handler that has been bound in order to be able to remove it again. – Codekie Jul 09 '19 at 14:42
  • @Codekie is right, see this answer: https://stackoverflow.com/a/10030771/220060, and here is a work-around (which modifies `Element.prototype` such that `addEventListener` and `removeEventListener` mainain an listener list): https://github.com/colxi/getEventListeners/blob/master/src/getEventListeners.js – nalply Jul 11 '19 at 14:53