Events

Run code when users click, type, submit, scroll, or interact.

Modern websites are interactive because they can respond to user actions. When a user clicks a button, types into a form, moves the mouse, or presses a key, JavaScript can detect these actions and perform specific tasks.

These actions are known as events, and the process of responding to them is called event handling.

What Is an Event?

An event is an action that occurs in the browser.

  • Clicking a button
  • Typing in a text field
  • Moving the mouse
  • Submitting a form
  • Pressing a keyboard key
  • Loading a webpage

What Is Event Handling?

Event handling is the process of executing JavaScript code when an event occurs. JavaScript listens for events and performs actions when those events happen.

Adding an Event Listener

HTML

html
<button id="myButton">Click Me</button>

JavaScript

javascript
let button = document.getElementById("myButton");

button.addEventListener("click", function() {
    console.log("Button clicked!");
});

Common Types of Events

Click Event

javascript
button.addEventListener("click", function() {
    alert("Button clicked!");
});

Input Event

html
<input type="text" id="name">
javascript
let input = document.getElementById("name");

input.addEventListener("input", function() {
    console.log("User is typing...");
});

Keyboard Event

javascript
document.addEventListener("keydown", function() {
    console.log("Key pressed");
});

Mouse Event

javascript
document.addEventListener("mouseover", function() {
    console.log("Mouse moved over element");
});

Event Object

javascript
button.addEventListener("click", function(event) {
    console.log(event.type);
});

Output:

javascript
click

Real-World Example

HTML

html
<h2 id="message">Welcome!</h2>

<button id="changeBtn">Change Text</button>

JavaScript

javascript
let button = document.getElementById("changeBtn");

button.addEventListener("click", function() {
    document.getElementById("message").textContent =
        "Thank you for clicking!";
});

Event Bubbling

When an event occurs on a child element, it can also trigger events on its parent elements. This behavior is called event bubbling.

Summary

Events allow JavaScript to detect user actions such as clicks, typing, mouse movements, and form submissions. Event handling enables developers to respond to these actions and create interactive experiences.

Let's learn with DevBrainBox AI