ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

JavaScript Tutorial• 6 min read

JavaScript DOM & Events

Handling clicks, keyboard events, and altering page elements

The HTML DOM (Document Object Model) allows JavaScript to access and manipulate all the elements of an HTML document in response to user actions.

EventListeners in Action

addEventListener() is the preferred modern way to register event handlers.

It allows attaching multiple listeners to the same element without overwriting existing handlers.

Common events: click, input, change, submit, keydown, mouseover.

Live Character Counter Example
<div style="max-width: 320px; font-family: sans-serif;">
  <label for="msg">Type your message:</label>
  <textarea id="msg" maxlength="50" style="width: 100%; height: 60px; margin: 8px 0; padding: 6px;"></textarea>
  <div style="display: flex; justify-content: space-between; font-size: 13px;">
    <span id="charCount">0 / 50 characters</span>
    <span id="warning" style="color: #ef4444; display: none;">Almost full!</span>
  </div>

  <script>
    const textarea = document.getElementById("msg");
    const countDisplay = document.getElementById("charCount");
    const warning = document.getElementById("warning");

    textarea.addEventListener("input", (e) => {
      const len = e.target.value.length;
      countDisplay.innerText = `${len} / 50 characters`;
      warning.style.display = len >= 40 ? "inline" : "none";
    });
  </script>
</div>
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which method attaches an event handler function to an element without overwriting existing handlers?