Table of contents
1.
Introduction
2.
Syntax of Event Handling in JavaScript
3.
Common JavaScript Events
4.
JavaScript Events Examples
4.1.
Example 1: Changing Text on Click
4.2.
Example 2: Alert on Key Press
4.3.
Example 3: Animating an Element on Mouse Over
5.
JavaScript Event Handlers
5.1.
Inline Handlers
5.2.
DOM Level 0 Handlers
5.3.
DOM Level 2 Handlers: addEventListener
5.4.
Removing Event Handlers
6.
Frequently Asked Questions
6.1.
What is the difference between onclick and addEventListener?
6.2.
Can I remove an event handler added with addEventListener?
6.3.
Are there any events that can be handled only with addEventListener?
7.
Conclusion
Last Updated: May 24, 2024
Easy

Event Handling in Javascript

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In JavaScript, event handling is a crucial concept that allows developers to create interactive & responsive web pages. It enables the code to react to user actions, such as clicking a button, hovering over an element, or submitting a form. By understanding event handling, you can make your websites more engaging & dynamic. 

Event Handling in Javascript

In this article, we will learn the basics of event handling in JavaScript, including its syntax, common events, event handlers, & practical examples.

Syntax of Event Handling in JavaScript

Event handling in JavaScript is structured around listening & responding to user actions or browser events. The basic syntax involves selecting an element & attaching an event listener to it. Here's a simple structure:

element.addEventListener('event', functionToCall);
  • element is the HTML element you want to add the listener to.
     
  • 'event' is the name of the event you are listening for, such as 'click' or 'mouseover'.
     
  • functionToCall is the function executed when the event occurs.


For example, to respond to a button click:

let button = document.getElementById('myButton');
button.addEventListener('click', function() {
    alert('Button clicked!');
});


This code snippet first retrieves a button with the ID 'myButton'. It then adds an event listener that triggers an alert message when the button is clicked. This approach lets you separate the event triggering & handling logic, making the code cleaner & easier to maintain.

Common JavaScript Events

JavaScript supports a wide range of events that can be used to create interactive & dynamic web experiences. Here are some of the most commonly used events:

  1. click: Triggered when an element is clicked.
     
  2. mouseover: Occurs when the mouse pointer is moved onto an element.
     
  3. mouseout: Activated when the mouse pointer is moved out of an element.
     
  4. keydown: Fired when a key is pressed down.
     
  5. keyup: Occurs when a key is released.
     
  6. load: Fired when the document or a resource has finished loading.
     
  7. resize: Triggered when the window is resized.
     
  8. scroll: Occurs when the user scrolls through a scrollable element.
     

Each of these events can be attached to elements through the addEventListener method we discussed in the syntax section. For example, to handle mouse over on an image:

let image = document.getElementById('myImage');
image.addEventListener('mouseover', function() {
    console.log('Mouse is over the image!');
});


This code will log a message to the console whenever the mouse hovers over the specified image. By using these events, you can tailor the behavior of your webpage to respond to user actions, making your site more interactive & responsive to user needs.

JavaScript Events Examples

To better understand how JavaScript events work in real-world scenarios, let's explore some practical examples that you can implement in your projects.

Example 1: Changing Text on Click

Suppose you have a paragraph on your webpage that you want to update when a user clicks on it. Here's how you can set it up:

// HTML element
<p id="demo">Click me to change text!</p>
// JavaScript code
let paragraph = document.getElementById('demo');
paragraph.addEventListener('click', function() {
    this.textContent = 'Text updated!';
});


In this example, clicking on the paragraph with the ID "demo" changes its text to "Text updated!". This simple interaction can enhance the user experience by making the webpage react to the user's actions.

Example 2: Alert on Key Press

This example will show how to trigger an alert when a specific key, like the Enter key, is pressed:

// JavaScript code
document.addEventListener('keydown', function(event) {
    if (event.key === 'Enter') {
        alert('Enter key was pressed!');
    }
});


By listening to the keydown event on the entire document, this script checks if the pressed key is the Enter key & displays an alert if true. This can be particularly useful in forms or interactive elements that react to keyboard inputs.

Example 3: Animating an Element on Mouse Over

Animating elements on mouse events can make a website feel more dynamic. Here’s an example where an element grows in size when the mouse hovers over it:

// HTML element
<div id="animateBox" style="width:100px; height:100px; background-color:blue;"></div>
// JavaScript code
let box = document.getElementById('animateBox');
box.addEventListener('mouseover', function() {
    this.style.width = '150px';
    this.style.height = '150px';
});
box.addEventListener('mouseout', function() {
    this.style.width = '100px';
    this.style.height = '100px';
});


This code makes a blue box grow larger when the mouse is over it & return to its original size when the mouse leaves. It's a straightforward way to add visual feedback based on user interaction.

JavaScript Event Handlers

Event handlers in JavaScript are functions that are called when an event occurs. These functions are crucial for responding to user interactions like clicks, key presses, & mouse movements. Let's break down how to use event handlers effectively.

Inline Handlers

One way to assign an event handler is directly in the HTML:

<button onclick="alert('You clicked me!')">Click Me!</button>


This method, known as an inline handler, allows you to quickly add functionality to an element. However, it mixes HTML with JavaScript, which can make the code harder to maintain as projects grow.

DOM Level 0 Handlers

You can also assign event handlers using JavaScript directly through the DOM:

let button = document.getElementById('myButton');
button.onclick = function() {
    alert('Button clicked!');
};


This approach is simple & straightforward, allowing you to keep your JavaScript code separate from HTML, but it only allows one handler per event type per element.

DOM Level 2 Handlers: addEventListener

The most flexible & widely recommended method is using addEventListener. This function allows multiple handlers per event & provides better control over the event's properties:

let button = document.getElementById('myButton');
button.addEventListener('click', function() {
    console.log('First handler');
});
button.addEventListener('click', function() {
    console.log('Second handler');
});


With addEventListener, multiple functions can respond to the same event on the same element without overriding each other, allowing for more complex interactions.

Removing Event Handlers

You can also remove event handlers when they are no longer needed using removeEventListener. This is useful for optimizing performance & avoiding memory leaks:

let button = document.getElementById('myButton');
let handleClick = function() {
    alert('Button clicked!');
    button.removeEventListener('click', handleClick);
};
button.addEventListener('click', handleClick);


In this example, the event handler is removed after the button is clicked once, preventing any further alerts from this button.

Frequently Asked Questions

What is the difference between onclick and addEventListener?

onclick assigns an event handler directly to an element, which can only handle one function at a time. If another function is assigned, it will override the previous one. addEventListener, however, allows multiple event handlers for the same event on the same element & offers more control over the event handling process.

Can I remove an event handler added with addEventListener?

Yes, you can remove an event handler using removeEventListener. It requires the same function reference used when adding the event, so it's important to define your event handlers as separate functions if you plan to remove them later.

Are there any events that can be handled only with addEventListener?

While most events can be handled using both methods, some newer event types, especially those related to HTML5 features like the animationend event, are often only reliably handled using addEventListener due to its advanced capabilities & support across different browsers.

Conclusion

In this article, we talked about event handling in JavaScript. We started with the basic syntax, after that we discussed some common events that can enhance web interactions. We looked into practical examples to demonstrate how these events can be implemented to make web pages interactive. Finally, we learned different methods to handle these events, emphasizing the flexibility & power of using addEventListener for setting up and removing event handlers. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass