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>
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)';
});
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>
JS
function change()
document.body.style.background = 'linear-gradient(#85FFBD, #FFFB7D)';
);
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.
How to make a custom cursor + cursor hover effects
Lens ・ Dec 27 '22
How to make a dark mode toggle with CSS and Javascript
Lens ・ Dec 10 '22
With all that done if you have any questions or things to add comment them below!
Top comments (0)