Event Handling in JavaScript
Understanding Listeners & Interactions



What is Event Handling in JavaScript?

In JavaScript, event handling refers to capturing user actions (like clicks, keypresses, or mouse movement) and responding to them through functions called event listeners.

Events are how users interact with web pages. When a user clicks a button, presses a key, or hovers over an element, an event occurs. JavaScript lets you listen for these events and run specific code in response.

Why Use addEventListener?

The addEventListener() method allows you to attach a function to an element to respond to a specific event.

Syntax:

element.addEventListener(eventType, callbackFunction);

This approach is preferred over inline handlers because:

Example 1: Click Event Listener

Let’s simulate clicking a button in the browser using pure JavaScript (console-based). We'll manually create a button in the DOM and then handle a click event.


// Create a button element dynamically
const button = document.createElement('button');
button.textContent = "Click Me";
document.body.appendChild(button);

// Add event listener to the button
button.addEventListener("click", function() {
  console.log("Button was clicked!");
});
    

Output:

Button was clicked!

Question: Can we attach more than one event listener to the same element?

Answer: Yes! addEventListener supports multiple listeners of the same type.


button.addEventListener("click", function() {
  console.log("Second click handler!");
});
    

Output:

Button was clicked!
Second click handler!
    

Example 2: Mouseover and Mouseout

Let’s listen to mouse movements on a div-like element created in JavaScript.


// Create a div element
const div = document.createElement('div');
div.textContent = "Hover over me!";
div.style.padding = "20px";
div.style.border = "1px solid black";
document.body.appendChild(div);

// Add mouseover and mouseout events
div.addEventListener("mouseover", () => {
  console.log("Mouse is over the div.");
});

div.addEventListener("mouseout", () => {
  console.log("Mouse has left the div.");
});
    

Output:

Mouse is over the div.
Mouse has left the div.
    

Example 3: Keydown Event

Detecting which key the user presses on the keyboard using the keydown event.


document.addEventListener("keydown", function(event) {
  console.log("You pressed: " + event.key);
});
    

Output:

You pressed: a

Example 4: Removing Event Listeners

Sometimes, you may want to remove a listener after it runs once. For this, you need to use a named function.


function sayHello() {
  console.log("Hello!");
  button.removeEventListener("click", sayHello); // Remove after first click
}

button.addEventListener("click", sayHello);
    

Output:

Hello!
// Subsequent clicks will not trigger this again
    

Question: What if you attach a listener to a non-existing element?

Answer: JavaScript will throw an error if the element doesn’t exist at the time of attachment. Always ensure elements are in the DOM before attaching listeners.

Points to Remember



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M