TExcelTAD
Home › JavaScript › JS Events

JavaScript Events

An event is something that happens on a web page: the user clicks a button, types in a box, moves the mouse, or the page finishes loading. JavaScript can listen for events and run a function — an event handler — when one occurs. This is what makes pages interactive.

Common events

Event Fires when…
click an element is clicked (or activated with Enter/Space on a button)
dblclick an element is double-clicked
input the value of an <input>/<textarea> changes as you type
change a form control's value is committed (e.g. a select is changed)
submit a form is submitted
keydown / keyup a key is pressed / released
mouseover / mouseout the pointer enters / leaves an element
focus / blur an element gains / loses keyboard focus
load the page (or an image) has finished loading

Event handler attributes

The simplest way to react to an event is an HTML attribute named on + the event name. The attribute's value is JavaScript code:

html · try it yourself
<button onclick="this.textContent = 'Clicked!'">Click me</button>
<button ondblclick="this.style.background = 'gold'">Double-click me</button>
<p onmouseover="this.style.color = 'crimson'" onmouseout="this.style.color = ''">
  Hover over this sentence.
</p>

Inside an attribute handler, this is the element that the handler is attached to.

Calling a function

For anything longer than one line, call a named function from the attribute:

html · try it yourself
<p>Count: <span id="count">0</span></p>
<button onclick="addOne()">+1</button>
<button onclick="reset()">Reset</button>
<script>
  let count = 0;
  function addOne() {
    count++;
    document.getElementById("count").textContent = count;
    console.log("count is now", count);
  }
  function reset() {
    count = 0;
    document.getElementById("count").textContent = count;
  }
</script>

addEventListener — the recommended way

Mixing JavaScript into HTML attributes gets messy, and an attribute can hold only one handler. The modern approach keeps the HTML clean and attaches handlers from a script with addEventListener(eventName, handlerFunction):

html · try it yourself
<label>Your name: <input id="name" placeholder="Type here"></label>
<p id="preview">Hello, stranger!</p>
<script>
  const input = document.getElementById("name");
  const preview = document.getElementById("preview");

  input.addEventListener("input", () => {
    const name = input.value.trim() || "stranger";
    preview.textContent = `Hello, ${name}!`;
  });
</script>

The input event fires on every keystroke, so the greeting updates live.

The event object

Handlers receive an event object describing what happened: which key was pressed, where the mouse was, which element was clicked. Here it's used to show the key and mouse position:

html · try it yourself
<p>Press any key, or click inside the box.</p>
<div id="box" style="height:100px;border:2px dashed #888;padding:8px">Click me</div>
<script>
  document.addEventListener("keydown", (event) => {
    console.log("key:", event.key);
  });
  document.getElementById("box").addEventListener("click", (event) => {
    console.log("clicked at", event.offsetX, event.offsetY);
  });
</script>

Note: Click inside the frame first so it receives your key presses.

Preventing default behaviour

Some events have a built-in action: a link navigates, a form submits and reloads the page. Call event.preventDefault() to stop it and handle things yourself:

html · try it yourself
<form id="signup">
  <input name="email" type="email" placeholder="you@example.com" required>
  <button>Sign up</button>
</form>
<p id="status"></p>
<script>
  document.getElementById("signup").addEventListener("submit", (event) => {
    event.preventDefault();               // no page reload
    const email = event.target.email.value;
    document.getElementById("status").textContent = "Thanks, " + email + "!";
  });
</script>

The HTML DOM section of this course goes much deeper: event bubbling, delegation, removing listeners and more.

Test yourself

Which event fires on every keystroke in a text input?

  1. change
  2. input
  3. submit
  4. load

Why is addEventListener preferred over onclick="…" attributes?

  1. It is faster to type
  2. It keeps JavaScript out of HTML and allows multiple handlers
  3. Attributes don't work in modern browsers
  4. It runs before the page loads

What does event.preventDefault() do in a submit handler?

  1. Deletes the form
  2. Stops the browser's default submit and page reload
  3. Stops all other JavaScript
  4. Clears the inputs