Intro to DOM Event Listeners

An event listener is a piece of Javascript code that only runs when a specific event is executed. The types of events range from button presses to keystrokes to hovering and more! 

In this tutorial, to go over Event Listeners, I’m going to walk through building 2 different (extremely simple) JS projects that use two different kinds of event listeners.

Because I want to keep things simple, I’m going to be using jQuery as opposed to plain JS for this tutorial. Once you’re familiar with jQuery syntax and usage, it’s a lot easier to transition to understanding it that way.

Onclick

The event listener I use the most frequently is definitely onclick. This is triggered when something specific on the page is clicked.

For this page, I’m going to build a counter that increments when you click a button.

To start with, I’m going to create two elements in my HTML: a button, and a div. When the button is clicked, the number in the div will increment. Let’s start out by just putting the number “0” inside of the div, beside the button. Assign both elements an ID.

<button id=”btn”>Click me</button> <br> <div id=”output”>0</div>
Code language: HTML, XML (xml)

Then, make sure you have jQuery loaded in your CodePen. You can do this either by clicking on the gear beside the Javascript and under ‘add external scripts/pens’, type in jQuery.

Alternatively, (or if you’re working elsewhere) you can paste this at the top of your HTML:

<script src=<a href="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js">https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js</a>”></script>
Code language: HTML, XML (xml)

The first thing we must do is identify which element we want to attach the event listener to. Since we want the code to run when we click the button, I’m using the ‘#btn’ id.

Pretty much everything you do with jQuery, you’re manipulating elements. You’ll almost always want to start out with $(#item), selecting the id or class of the element.

$('#btn').on("click", function() { console.log('test'); });
Code language: JavaScript (javascript)

You can test the above code by pasting it into the Javascript box on CodePen, or putting it between <script></script> tags at the bottom of your webpage. Check the console for output.

Important note:

In some circumstances, (usually outside of CodePen) you might find that your event listener doesn’t work. To fix this, put ALL of your event listener code between this code:

$( document ).ready(function() { // your code here });
Code language: JavaScript (javascript)

If you want to understand why this makes a difference, look up Javascript DOM event propagation!

I always like to test my event listeners with a console message before proceeding.

Inside of the event listener, we want to increment our number, but first we have to define it somewhere.

We want to define it outside of the event listener. If we defined it inside, the number would never increment since every time you click, it would reset as zero.

Once we define it, we just need to use the .text() DOM method on our #output div and increment the variable by one.

// define the starting number // (it's important this is OUTSIDE of the event listener) var num = 0; $('#btn').on("click", function() { // change output text to num + 1 $('#output').text(num++); });
Code language: JavaScript (javascript)

Using ++ at the end of a variable will always increment it by one!

Below is a live demo of the final product.

See the Pen Increment onclick by Sadness (@sadness97) on CodePen.

It’s not much, but it does what it’s supposed to do!

Mouseover

Next, we’re going to look at the mouseover event, which listens for a mouse hover. For this, we’ll change the background image to a pattern when it is hovered over.

If you’re using a new pen, be sure to set jQuery up before proceeding.

Then, add three image elements to the HTML:

<img src="https://sadhost.neocities.org/images/tiles/leavesbg.gif"> <img src="https://sadhost.neocities.org/images/tiles/tumblr_inline_ml2g0lBiCI1qz4rgp540.gif"> <img src="https://sadhost.neocities.org/images/tiles/tumblr_inline_mll0keW1Af1r53miq540.gif">
Code language: HTML, XML (xml)

Next, we’ll create our event listener, making sure to use console.log() to test that it’s working.

$('img').on('mouseover', function() { console.log('test'); })
Code language: JavaScript (javascript)

Here, we’re using the img tag to grab the item. If you have other images on the same page, this code will apply to all of them. You can always assign classes or reference the parent (wrapper) div in the selector.

Next, we want to grab the URL of each image, because we want to assign it to the background.

This is a great time to use the variable $(this). When used within an event listener, $(this) refers to the item that is being manipulated. In this case, it’s the image itself being hovered over.

On $(this), we can use the .attr(‘src’) method to get the src of the image, which has the link we need.

$('img').on('mouseover', function() { var url = $(this).attr('src'); console.log(url); });
Code language: JavaScript (javascript)

In the example above, I’m using console.log to log the URL so I can see it and make sure it looks correct.

The last thing we need to do is change the CSS of the body element to the URL of the image being hovered over. To do this, we can use the .css() method to change the background with JS. We’ll need to use concatenation, which is combining our variable with the CSS code.

Our final code will look like this:

$('img').on('mouseover', function() { var url = $(this).attr('src'); $('body').css("background-image", "url('" + url + "')") })
Code language: JavaScript (javascript)

The .css() method has two parameters: the property and the value. The property we want to change is background-image and the value is url(‘https://myurl.jpg’);

Here is a live CodePen demo:

See the Pen Change background on hover by Sadness (@sadness97) on CodePen.

Conclusion

These examples were extremely simple, and are only meant to serve as an example of how to use event listeners.

You can find more comprehensive documentation of the different types of event listeners on this page. I recommend just playing around with different ones and making small things you might be able to build upon in the future.



Hey, thanks for reading! If you have any questions, you can leave me a comment and I always try to reply.

If you have any suggestions on how I can improve this article, please let me know!

This website is not monetized in any way. It purely exists to help others on their web-building journey. However, if you have the means to donate toward my server costs, I have a ko-fi account where I accept tips.

Leave a Comment