JavaScriptLesson 13 of 18

JavaScript Events

An event is something that happens in the browser: a click, a key press, a mouse move, or a form submit. JavaScript can listen for events and run code when they occur. That is the bridge between the visitor and your code, and it is what makes pages interactive instead of static.

An event is something that happens in the browser: a click, a key press, a mouse move, or a form submit. JavaScript can listen for events and run code when they occur. That is the bridge between the visitor and your code, and it is what makes pages interactive instead of static.

The simplest way to react is the onclick property. Set it on an element and it fires when the user clicks. The modern tool is addEventListener, which separates the event name from the code. Use addEventListener in new code: it lets you attach several handlers to one element and remove them later, which onclick cannot do.

A classic mistake is calling the handler instead of passing it: addEventListener("click", run()) fires run immediately and never again, because the parentheses run it right away. Pass the function without parentheses, addEventListener("click", run), and the browser calls it for you when the event fires. Every event handler follows this rule.

The click event

Click is the most common event. addEventListener takes two arguments: the event name as a string, and the function to run when it fires. The handler function receives an event object that tells you what was clicked and where.

JS
document.getElementById("btn").addEventListener("click", function (event) {
  console.log("Clicked at", event.clientX);
});

Reacting to typing

The input event fires every time the value of a field changes, on every keystroke. It is perfect for live search, character counters, and previews that update as the user types, with no button needed.

JS
const field = document.getElementById("name");
field.addEventListener("input", function () {
  console.log(field.value);
});

Syntax

JS
document.getElementById("btn").addEventListener("click", function () {
  console.log("Button clicked!");
});

addEventListener("click", fn()) Calls Immediately

Passing fn() runs now, not on click — pass fn without ().

JS
btn.addEventListener("click", fn) // not fn()

Good to know

  • Events fire when users click, type, or move the mouse.
  • addEventListener lets you attach several handlers to one element.
  • Pass handlers without parentheses, or they run immediately.
  • The input event fires on every keystroke.
Try it Yourself Edit the code, press Run, then check what changed in the Result.
Ready
Code
Result

Practice makes it stick

Open the Playground and build your own page with the tags you just learned.

→ Open Playground