Tutorials

JavaScript Tutorial

All Tutorials Learning Tools Login

JavaScript Tutorial · Chapter 5 of 8

JS Events

Respond to user actions.

addEventListener connects an element event such as click to a function.

Common beginner events: click, submit, input, and keydown.

Events sample Try it Yourself »
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JS Events</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>Event Practice</h1>
    <p id="status">Waiting for a click...</p>
    <button id="countButton">Count Clicks</button>
    <script src="script.js"></script>
</body>
</html>
style.css
body {
    font-family: Arial, sans-serif;
    padding: 32px;
    background: #f8fafc;
}

button {
    padding: 10px 16px;
    border: 0;
    border-radius: 8px;
    background: #16675f;
    color: white;
}
script.js
let clicks = 0;
const button = document.getElementById("countButton");
const status = document.getElementById("status");

button.addEventListener("click", function () {
    clicks += 1;
    status.textContent = "Button clicked " + clicks + " time(s).";
});

Classroom Tips

  • Select elements after they exist in the page.
  • Misspelled ids are a common bug.