Events & addEventListener
React to clicks, typing, hovering and more — the proper, professional way to handle interaction.
What you will learn
- Handle events with addEventListener
- Respond to clicks and input
- Read the event and the element
The professional way to handle events
Instead of inline onclick, attach handlers in JavaScript with addEventListener. It keeps HTML and behaviour separate and lets you add many handlers.
<button id="btn">Click me</button>
<p id="count">Clicks: 0</p>
<script>
let clicks = 0;
const btn = document.getElementById("btn");
btn.addEventListener("click", function() {
clicks++;
document.getElementById("count").textContent = "Clicks: " + clicks;
});
</script>We keep a counter clicks starting at 0. btn.addEventListener("click", function(){...}) says "every time this button is clicked, run this function". Inside, clicks++ bumps the count by one and we rewrite the paragraph to show the new total. The function does not run now — it waits and fires on each click.
Note: Output: Starts at: Clicks: 0 After 3 clicks: Clicks: 3
Common events
| Event | Fires when |
|---|---|
click | An element is clicked |
input | A field’s value changes |
submit | A form is submitted |
mouseover / mouseout | The mouse enters / leaves |
keydown | A key is pressed |
The input event fires on every keystroke, so we can react as the user types. Try typing your name in the box.
<input id="name" placeholder="Type your name">
<p id="live">Hello, stranger!</p>
<script>
document.getElementById("name").addEventListener("input", function(e) {
document.getElementById("live").textContent = "Hello, " + (e.target.value || "stranger") + "!";
});
</script>Each time you type, the handler runs. e.target is the input box itself, and e.target.value is whatever is currently typed in it. The || "stranger" part means "if the box is empty, use the word stranger instead". We drop that into the greeting, which updates instantly with every keystroke.
Note: Output: Empty box: Hello, stranger! Type "Asha": Hello, Asha!
Tip: Inside a handler, e.target is the element that fired the event, and e.target.value is what the user typed. This is the foundation of all interactive UIs — and React builds directly on it.
Q. Which method attaches an event handler the professional way?
✍️ Practice
- Build a click counter using
addEventListener. - Make a live character counter for a textarea using the
inputevent.
🏠 Homework
- Build a button that toggles a “dark mode” class on the page when clicked.