JavaScript responds to what the user does on a page: clicks, key presses, mouse movements and form changes. These actions are events.

Events

An event is an action or occurrence in the browser that JavaScript can respond to. Mouse events: click, dblclick, mouseover, mouseout, mousemove, mousedown and mouseup. Keyboard events: keydown and keyup. Form events: submit, change, input, focus and blur. Window events: load (the page has finished loading), resize and scroll. A function that runs when an event occurs is an event handler or listener.

Definition: Event handler. A function that is run by the browser when a particular event, such as a click or a key press, occurs on an element.

Attaching Handlers

There are three ways. HTML attributes: <button onclick="greet()">. This is simple but mixes code with HTML. DOM properties: btn.onclick = greet;. Only one handler per event can be set this way. addEventListener: btn.addEventListener("click", greet);. This is the recommended way: it allows several handlers for one event, and they can be removed with removeEventListener.

The Event Object

A handler receives an event object, often named e, with details of the event: e.target (the element that received the event), e.type, e.key (the key pressed), and mouse coordinates e.clientX and e.clientY. e.preventDefault() stops the browser's default action, such as submitting a form or following a link, which is used in form validation. e.stopPropagation() stops the event from bubbling up to parent elements.

Event Bubbling

When an event occurs on an element, it first runs the element's handlers and then bubbles up through its ancestors. This allows event delegation: one listener on a parent handles events from all its children, using e.target to tell which child was clicked.

Table 3.4: Common events

Event Occurs when Typical use
click Element is clicked Buttons
mouseover / mouseout Pointer enters / leaves Hover effects
keyup Key is released Live search, counters
change Input value changes Drop-down choices
submit Form is submitted Validation
load Page finishes loading Start-up code

Example 3.4: Five events on one page

Problem: Write a page that uses five events: click on a button to count clicks, mouseover and mouseout on a box to change its colour, keyup in a text box to show the number of characters, and change on a drop-down to show the choice.

Solution:

  1. Select the elements with getElementById.
  2. Add listeners for click, mouseover, mouseout, keyup and change.
  3. In each handler, update the text or style of the matching element.

Result: The page reacts to each of the five events.

<button id="btn">Click me</button> <span id="count">0</span>
<div id="box"
     style="width:120px;height:50px;background:#DEEAF6"></div>
<input id="txt"> <span id="len">0 characters</span>
<select id="city">
  <option>Delhi</option><option>Gurugram</option>
</select>
<p id="choice"></p>
<script>
  let n = 0;
  const $ = id => document.getElementById(id);
  $("btn").addEventListener("click",
      () => $("count").textContent = ++n);
  $("box").addEventListener("mouseover",
      e => e.target.style.background = "gold");
  $("box").addEventListener("mouseout",
      e => e.target.style.background = "#DEEAF6");
  $("txt").addEventListener("keyup", e =>
      $("len").textContent = e.target.value.length + " characters");
  $("city").addEventListener("change", e =>
      $("choice").textContent = "You chose " + e.target.value);
</script>

Common mistakes

  • Writing onclick="greet" without the brackets in an HTML attribute.
  • Calling the handler when attaching it, as in addEventListener("click", greet()).
  • Forgetting preventDefault() when a form must not submit.

Key takeaways

  • Events are user or browser actions; handlers respond to them.
  • addEventListener is the recommended way to attach handlers.
  • The event object gives target, type, key and coordinates.
  • Events bubble up, which allows delegation.

Practice questions

  1. What is an event?
  2. Why is addEventListener preferred?
  3. What does e.preventDefault() do?

Answers to the practice questions

  1. An action or occurrence in the browser, such as a click, that JavaScript can respond to.
  2. It allows several handlers per event and keeps code separate from HTML.
  3. It stops the browser's default action for the event, such as submitting a form.

Sources

  • Official BCA syllabus Web Technologies, course code 25BCA402SEC02, Unit III