DEV Community

Cover image for JavaScript Event Listeners for Beginners
Mark "niteCoda" Freeman
Mark "niteCoda" Freeman

Posted on

JavaScript Event Listeners for Beginners

What Are Events and Listeners?

Visitors to our websites, and users of our applications, are continuously interacting with elements of the Document Object Module (DOM), whether they realise it or not.

When these interactions occur, the elements themselves emit event actions. As JavaScript developers, we're able to listen for these events using the JavaScript method for event listeners and then handle them with appropriate and well-timed responses. Assuming that's our our aim, and it certainly should be.

Why Should We Listen for Element Events?

Responding to user activity can greatly enhance user experience and interactivity leading to improved engagement.

What are Events Exactly?

Events vary according to element type, most are obvious but some not so. They include, for example;

  • Mouse events:- such as mouseover, mousedown, mouseup and click;
  • Keyboard events:- such as keydown and keyup;
  • Form events:- such as focus and submit;
  • Window events:- such as scroll and resize;
  • to name but a few.

A detailed explanation to writing your first simple event listener:

Step 1 - Target the element and declare a new variable.

The very first step in preparing our code for listening and handling events, is to declare a variable for the element that will be emitting the event we're interested in. In the following simple example, that element is a button with the class click-me.

We'll declare a variable with an intuitive name; clickMe and use the button's class of click-me to select the element from within the document, using the JavaScript method .querySelector():

const clickMe = document.querySelector('.click-me');
Enter fullscreen mode Exit fullscreen mode

2. Call the click-me variable that we've just declared for the button:

click-me
Enter fullscreen mode Exit fullscreen mode

3. Next, we attach to that variable, the JavaScript method for event listening .addEventListener().

click-me.addEventListener();
Enter fullscreen mode Exit fullscreen mode

The event listener takes in two parameters, comma-separated, inside the parenthesis:

  1. - The first is the emit event which sets up the listener. In this example we'll listen for a click event.
  2. - The second, a function that will be called to action when the specified event occurs. This function is known as a callback function and in this example, it has no name and so, is anonymous.

4. Add the event Parameters

Our Parameters in this case are click, and an empty function function().

click-me.addEventListener('click', function());
Enter fullscreen mode Exit fullscreen mode

5. Add a code block:

Next We'll open up a code block { } which will contain the code for the action we wish to take place in response to the event:

click-me.addEventListener('click', function() {  });
Enter fullscreen mode Exit fullscreen mode

6. Add a callback response

Inside the code block, we'll simply output an appropriate message to the console using console.log();

clickMe.addEventListener('click', function() {
  console.log(`the button with class 'click-me' button was clicked`);
});
Enter fullscreen mode Exit fullscreen mode

Our event listener is now complete with response and feedback.

This simple event listener will execute a log to the console every time the button is clicked. It will also work if the user focuses the button using tab, and presses the enter key.

A simple way to remember event listeners

If all of this seems too much to remember at first, a simple way to remember the role and key ingredients of an event listener is this:

  1. Get click-me button
  2. Listen click event
  3. Do console.log

Hopefully, this will help you along your own path towards JavaScript mastery.

Oldest comments (1)

Collapse
 
raddevus profile image
raddevus

A good quick explanation. Thanks for writing it up. 👍🏽
If you get a chance, check out my article where I created an emoji app. Thanks and welcome to dev.to.