Episode 40 of 46

Intro to JavaScript Events

Understand the event system — how JavaScript responds to user interactions.

Events are things that happen on a web page — clicks, key presses, mouse movements, form submissions, and more. JavaScript can listen for these events and run code in response.

Adding Event Listeners

let button = document.querySelector("#myBtn");

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

Common Events

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

The Event Object

button.addEventListener("click", function(event) {
    console.log(event.type);      // "click"
    console.log(event.target);    // The clicked element
    console.log(event.clientX);   // Mouse X position
    console.log(event.clientY);   // Mouse Y position
});

Keyboard Events

document.addEventListener("keydown", function(e) {
    console.log("Key pressed:", e.key);
    console.log("Key code:", e.code);

    if (e.key === "Enter") {
        console.log("Enter pressed!");
    }

    if (e.ctrlKey && e.key === "s") {
        e.preventDefault();
        console.log("Ctrl+S — saving!");
    }
});

Removing Event Listeners

function handleClick() {
    console.log("Clicked!");
}

button.addEventListener("click", handleClick);
button.removeEventListener("click", handleClick);

Note: You must pass the same function reference to remove it. Anonymous functions cannot be removed.