JavaScript 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

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.

Key Takeaways

  • Events is an important topic to understand.
  • Start with small examples and practice one step at a time.
  • Use the idea in simple projects so it becomes easier to remember.