DEV Community

Lens
Lens

Posted on

A short guide on Event Listeners

How it works

Event listeners are used to make an event or action happen when the user does something. For example a common event listner is click where when the user clicks something an event or action happens. To make an event listener you have to use the method addEventListner on a variable or element. Inside the method is the handler and the function. The handler is what type of eventListner you want like click, while the function is the event that happends when you click it. On the example below when we click the header the background goes from red to a green gradient.

HTML

<html>
<body>
<h1>Click Me!</h1>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

JS

//We put the h1 element in a variable
var header = document.querySelector('h1');

header.addEventListener('click', function(){
  document.body.style.background = 'linear-gradient(#85FFBD, #FFFB7D)';
});
Enter fullscreen mode Exit fullscreen mode



Event handlers

click isn't the only handler!

  • dbclick causes an event when something is double clicked
  • scroll causes an event when something is scrolled
  • change causes an event when something changes
  • mousemove when the mouse is moving over an element
  • mouseout when the mouse stops moving on an element
  • mousedown when the mouse is pressing down on something
  • mouseup when the mouse is pressing up at something
  • drag when something is being dragged around

Event Attributes

Another way to make an event without the eventListener is with attributes. Some have different names than the handlers like how dbclick as an attribute is ondbclick but they do the same thing. For example in the codepen above instead of using an eventListener with a click handler we'll just make a function where the body turns to a green gradient then make give the header an 'onclick' attribute with the function in it.

HTML

<html>
<body>
<h1 onclick="change()">Click Me!</h1>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

JS

function change()
document.body.style.background = 'linear-gradient(#85FFBD, #FFFB7D)';
);
Enter fullscreen mode Exit fullscreen mode

Conclusion

With event listeners you can make you website intereactive and fun to use. If you need more examples on how to use them i made a blog on using mouse events to make a custom cursor and a blog on making a dark mode toggle.



With all that done if you have any questions or things to add comment them below!

Top comments (0)