Skip to main content
JavaScript Basics
CHAPTER 17 Beginner

JavaScript Events

Updated: May 12, 2026
25 min read

# JavaScript Events

Websites are not meant to be static documents; they are meant to be interacted with. When a user hovers over a card, clicks a button, types in a search bar, or scrolls down the page, the browser fires an Event.

In this chapter, we will learn how to "listen" for these events and execute JavaScript code in response to them.

1. Introduction

HTML events are "things" that happen to HTML elements. JavaScript can be instructed to listen for these events using Event Listeners.

Previously, we used onclick="myFunction()" directly in our HTML. While this works, it violates the principle of separation of concerns (mixing structure with behavior). Modern JavaScript uses addEventListener() to handle events entirely inside the .js file.

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Identify common HTML events (clicks, hovers, keyboard inputs).
  • Attach events using addEventListener().
  • Use the Event object to get information about the interaction.
  • Remove event listeners.
  • Build an Interactive Button Effects mini-project.

3. Common HTML Events

Here is a list of the most common events you will use:

  • Mouse Events: click, dblclick, mouseenter, mouseleave
  • Keyboard Events: keydown, keyup, keypress
  • Form Events: submit, change, input, focus, blur
  • Window Events: load, resize, scroll

4. addEventListener()

The addEventListener() method attaches an event handler to a specific element without overwriting existing event handlers.

javascript
12
// Syntax
element.addEventListener("event_name", function_to_run);

*Note: We drop the "on" prefix. It is click, not onclick.*

---

5. Real-world Examples & Code Snippets

Example 1: The Modern Click Event

HTML:

html
12
<!-- Example HTML -->
<button id="myBtn">Click Me</button>

JavaScript:

javascript
123456
// Example JavaScript
let btn = document.getElementById("myBtn");

btn.addEventListener("click", function() {
    alert("Button was clicked securely!");
});

Example 2: Calling a Named Function

Instead of writing the function directly inside the listener (an anonymous function), you can pass the name of an existing function.

javascript
1234567
// Example JavaScript
function turnRed() {
    document.body.style.backgroundColor = "red";
}

let btn = document.getElementById("colorBtn");
btn.addEventListener("click", turnRed); // Do NOT add () after turnRed!

*Why no ()? If you write turnRed(), the function runs immediately when the page loads, rather than waiting for the click.*

Example 3: Mouse Enter and Leave (Hover)

javascript
12345678910
// Example JavaScript
let box = document.getElementById("hoverBox");

box.addEventListener("mouseenter", function() {
    box.style.backgroundColor = "yellow";
});

box.addEventListener("mouseleave", function() {
    box.style.backgroundColor = "white";
});

Example 4: The Event Object (e or event)

When an event occurs, the browser automatically creates an Event Object containing massive amounts of data about the event (Where was the mouse? Which key was pressed?). It is passed as the first parameter to your function.

javascript
12345
// Example JavaScript
document.addEventListener("click", function(event) {
    console.log("X Coordinate: " + event.clientX);
    console.log("Y Coordinate: " + event.clientY);
});

Example 5: Keyboard Events (keyup)

Listening to what the user types.

html
123
<!-- Example HTML -->
<input type="text" id="searchBox" placeholder="Type here...">
<p id="output"></p>
javascript
1234567891011
// Example JavaScript
let search = document.getElementById("searchBox");

search.addEventListener("keyup", function(event) {
    document.getElementById("output").textContent = "You typed: " + search.value;
    
    // We can also check WHICH key was pressed!
    if (event.key === "Enter") {
        alert("You pressed Enter!");
    }
});

Example 6: The input Event (Real-time tracking)

Unlike keyup, the input event fires immediately every time the value of the input changes, even if they paste text with a mouse.

javascript
123456
// Example JavaScript
let nameInput = document.getElementById("name");

nameInput.addEventListener("input", function() {
    console.log("Current value is: " + nameInput.value);
});

Example 7: The change Event

The change event fires only when the user finishes interacting and "commits" the change (e.g., clicking away from the input, or selecting an option from a dropdown).

html
12345
<!-- Example HTML -->
<select id="colors">
    <option value="red">Red</option>
    <option value="blue">Blue</option>
</select>
javascript
1234
// Example JavaScript
document.getElementById("colors").addEventListener("change", function(e) {
    console.log("User selected: " + e.target.value);
});

Example 8: Form submit and preventDefault()

When a user submits an HTML form, the default browser behavior is to refresh the page. In modern apps, we want to stop this refresh and handle the data with JS. We use event.preventDefault().

html
12345
<!-- Example HTML -->
<form id="myForm">
    <input type="text" required>
    <button type="submit">Submit</button>
</form>
javascript
12345
// Example JavaScript
document.getElementById("myForm").addEventListener("submit", function(event) {
    event.preventDefault(); // STOPS the page from refreshing!
    console.log("Form submitted via JavaScript!");
});

Example 9: Multiple Listeners on One Element

You can attach multiple different events to the same element without overwriting them.

javascript
12345
// Example JavaScript
let btn = document.getElementById("myBtn");

btn.addEventListener("click", function() { console.log("Clicked!"); });
btn.addEventListener("mouseenter", function() { console.log("Hovered!"); });

Example 10: Event Delegation

If you have a list of 100 items, adding 100 event listeners is bad for performance. Instead, you add ONE listener to the parent <ul>, and let the events "bubble up".

html
12345678910111213141516
<!-- Example HTML -->
<ul id="parentList">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

<script>
// Example JavaScript
document.getElementById("parentList").addEventListener("click", function(event) {
    // e.target is the exact element that was clicked
    if (event.target.tagName === "LI") {
        console.log("You clicked: " + event.target.textContent);
    }
});
</script>

---

7. Common Mistakes for Beginners

  1. 1. Adding () to a named function in addEventListener:
btn.addEventListener("click", myFunc()); // BAD! Runs immediately. btn.addEventListener("click", myFunc); // GOOD! Runs on click.
  1. 2. Forgetting preventDefault() on forms: If you forget this, your JS code might run for a split second, but then the page refreshes and all your data is lost.
  1. 3. Using event.target vs event.currentTarget: target is the exact element clicked (maybe an icon inside a button). currentTarget is the element the listener is attached to (the button itself).

8. Best Practices

  • Always separate HTML and JS. Remove all onclick="" attributes from your HTML files.
  • Use event.preventDefault() on all forms.
  • Use Event Delegation when dealing with lists or dynamically created elements.

9. Mini Project: Interactive Button Effects

Let's build a UI with buttons that track mouse coordinates and generate ripple effects.

HTML:

html
12345678910111213141516171819202122232425262728293031323334353637383940414243
<!-- Example HTML -->
<!DOCTYPE html>
<html>
<head>
    <style>
        /* Example CSS */
        body { font-family: sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background: #222; margin: 0;}
        
        .magic-btn {
            position: relative;
            padding: 20px 40px;
            font-size: 20px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            overflow: hidden; /* Contains the ripple */
            outline: none;
        }

        /* The Ripple Circle */
        .ripple {
            position: absolute;
            background: rgba(255, 255, 255, 0.5);
            border-radius: 50%;
            transform: scale(0);
            animation: ripple-anim 0.6s linear;
            pointer-events: none; /* Ignore clicks on the ripple itself */
        }

        @keyframes ripple-anim {
            to { transform: scale(4); opacity: 0; }
        }
    </style>
</head>
<body>

    <button class="magic-btn" id="rippleBtn">Click for Ripple</button>

    <script src="events.js"></script>
</body>
</html>

events.js:

javascript
12345678910111213141516171819202122232425262728293031
// Example JavaScript
const btn = document.getElementById("rippleBtn");

btn.addEventListener("click", function(event) {
    // 1. Get click coordinates relative to the viewport
    let x = event.clientX;
    let y = event.clientY;
    
    // 2. Get button position relative to the viewport
    let buttonRect = btn.getBoundingClientRect();
    
    // 3. Calculate click coordinates relative to the button inside
    let xInside = x - buttonRect.left;
    let yInside = y - buttonRect.top;
    
    // 4. Create the ripple span element
    let circle = document.createElement("span");
    circle.classList.add("ripple");
    
    // 5. Position the ripple exactly where the user clicked
    circle.style.left = xInside + "px";
    circle.style.top = yInside + "px";
    
    // 6. Append to button
    btn.appendChild(circle);
    
    // 7. Remove the span after animation completes to keep DOM clean
    setTimeout(function() {
        circle.remove();
    }, 600);
});

10. Exercises

  1. 1. Create a <div> in HTML. Write JS to add an event listener that console logs "Hovering!" when the mouse enters it.
  1. 2. Add an event listener to the document that listens for keydown. If the user presses the "Escape" key, trigger an alert.
  1. 3. Why is event.preventDefault() necessary when dealing with HTML <form> submissions?

11. MCQs (Multiple Choice Questions)

Q1: What is the correct way to add a click event in modern JavaScript? A) btn.onClick = function() B) btn.addEventListener("click", function()) C) btn.attachEvent("click", function()) D) btn.addEventListener("onclick", function()) *Answer: B*

Q2: What is the purpose of the Event object (e) passed to an event listener? A) To stop the event. B) To hold data about the event (like mouse coordinates or keys pressed). C) To change the CSS of the element. D) To trigger a second event. *Answer: B*

Q3: Which event fires continuously as the user types into an input field? A) change B) submit C) input D) blur *Answer: C*

12. Interview Questions

Q: Explain Event Bubbling. *A: Event Bubbling is a mechanism where an event triggered on a deeply nested element (like a <span> inside a <button> inside a <div>) will "bubble up" and trigger listeners on all of its parent elements, all the way up to the document. You can stop this using event.stopPropagation().*

Q: What is Event Delegation? *A: Event Delegation is a pattern based on Event Bubbling. Instead of attaching 100 event listeners to 100 child elements, you attach ONE listener to the parent element. When a child is clicked, the event bubbles up to the parent, and you use event.target to figure out which child initiated the event.*

13. FAQs

Q: Should I use Arrow Functions for Event Listeners? *A: Yes, mostly. But be careful: in standard functions, this refers to the element that was clicked. In arrow functions, this is inherited from the surrounding scope, which can cause bugs if you rely on it. It is usually safer to use event.currentTarget.*

14. Summary

  • Use addEventListener(event, function) to listen for user interactions.
  • Common events: click, mouseenter, keyup, submit, input.
  • The Event object (event or e) contains data about the interaction.
  • event.target tells you exactly what element was interacted with.
  • Use event.preventDefault() to stop forms from refreshing the page.

15. Next Chapter Recommendation

Now that we know how to listen to forms and stop them from refreshing the page, we need to make sure the data users type is actually valid. In the next chapter, JavaScript Forms Validation, we will learn how to check passwords, verify emails, and secure our inputs.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·