JavaScript Events

1. What are Events?

Events are actions that occur in the browser, like clicking a button, typing in input, or moving the mouse. JavaScript can respond to these events using event handlers.

2. Event Types

// Mouse Events: click, dblclick, mouseover, mouseout
// Keyboard Events: keydown, keyup, keypress
// Form Events: submit, change, input, focus, blur
// Window Events: load, resize, scroll
        

3. addEventListener vs Inline Events

// Inline (not recommended)


// addEventListener (recommended)
let btn = document.getElementById("btn");
btn.addEventListener("click", () => alert("Clicked!"));
        

4. Example: Event Handling

let clickBtn = document.getElementById("clickBtn");
let nameInput = document.getElementById("nameInput");
let output = document.getElementById("output");

// Click event
clickBtn.addEventListener("click", () => {
    output.textContent = "Button Clicked!";
});

// Input event
nameInput.addEventListener("input", (e) => {
    output.textContent = "You typed: " + e.target.value;
});
        

Comparison Table: Event Binding

Feature Inline Event addEventListener
Syntax HTML attribute: onclick JS method: addEventListener
Multiple handlers Not allowed Allowed
Separation of concerns Mixes HTML & JS Keeps HTML & JS separate
Flexibility Limited High
Recommended No Yes
✅ Best Practice: Always use addEventListener to attach events. Avoid inline events for maintainable code.

Practice Questions

Test your understanding of JavaScript Events.

Easy

Q1: Attach a click event listener.

  • Select a button element with the ID myBtn.
  • Use addEventListener to attach a click event.
  • Log "Clicked!" to the console when triggered.
Easy

Q2: Compare inline events and addEventListener.

  • Explain the difference between an inline event handler (like onclick="...") and addEventListener().
  • Write a brief code example showing the preferred method.
Medium

Q3: Prevent the default action of an event.

  • Assume you have a link selected as const link = document.querySelector('a');.
  • Add a click event listener to it.
  • Use the appropriate event method to prevent the link from navigating.
  • Log a message to the console confirming navigation was prevented.
Medium

Q4: Stop event bubbling.

  • Explain what event bubbling is in the DOM.
  • Given a click event listener on an element with ID child, write the code to stop the event from bubbling up to its parent elements.
Hard

Q5: Implement event delegation.

  • Explain what event delegation is.
  • Write an example attaching a single click listener to a parent <ul> (ID: myList).
  • Inside the listener, check if the clicked target is an <li> element.
  • Log the text content of the clicked <li>.

Answer

Code: