TalentJR

🟨 JavaScript tutorial for beginners · Class 8 · Lesson 5 of 18 · Free

Events & Interactions – Make Pages React with JavaScript

⏱ About 35 minutes · ▶ run real JavaScript here — nothing to install · no sign-in

In this lesson you will

  • Run code when the user clicks, types or hovers, using addEventListener
  • Use the event object to find out which key or element was used
  • Build a counter and a live character counter on a real page

In Lesson 4 your JavaScript changed the page — but only once, as soon as it loaded. Real apps wait for you: a like button counts your taps, a chat box counts your letters as you type. That waiting-and-reacting is done with events.

How do I run JavaScript when a button is clicked?

An event is something that happens on the page: a click, a key press, the mouse moving. addEventListener tells an element: "when this event happens, run this function".

It takes two things: the event name as a string ("click") and a function. The function is called a handler. Here it is an arrow function from Lesson 3.

Press ▶ Run, then click the button a few times. The count lives in a let variable outside the handler, so it remembers between clicks.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Waiting for clicks...

💡 The console first shows only "Waiting for clicks...". Each click adds a new line.

Why doesn't my event handler run straight away?

addEventListener does not run the function. It only saves it, like leaving your number with a shopkeeper: "call me when the stock arrives".

The program carries on. Later, when the click happens, the browser calls your function.

Here a button is made in memory and clicked from code with .click(), so you can watch the order in the animation. Notice that "2. Listener added" prints before the handler's line.

🎬 How JavaScript thinks — step 1 of 13JavaScript is about to run line 1
▶const btn = document.createElement("button");
2let clicks = 0;
3console.log("1. Start");
4
5btn.addEventListener("click", () => {
6 clicks = clicks + 1;
7 console.log("Handler ran, clicks =", clicks);
8});
9console.log("2. Listener added");
10
11btn.click();
12btn.click();
13console.log("3. End, clicks =", clicks);
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
1. Start
2. Listener added
Handler ran, clicks = 1
Handler ran, clicks = 2
3. End, clicks = 2

What is the event object in JavaScript?

When the browser calls your handler, it passes one argument: the event object. Most people name it event or e.

It holds details. event.type is the kind of event. event.target is the element where it happened. For keyboard events, event.key is the key pressed.

One handler on the whole list can handle every button: event.target tells you which one was clicked.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Click a tiffin button.

💡 The if checks that a button was clicked, not the gap between buttons. Lesson 9 covers if fully.

How do I react to typing with JavaScript?

The "input" event fires every time the text in a box changes. It is perfect for live counters and search boxes.

The "keydown" event fires when a key is pressed down. event.key gives the key's name, like "a" or "Enter".

Type in the chat box below. The counter turns red when you go over 30 letters.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Start typing!

💡 condition ? a : b is a short if/else: if remaining < 0, use "red", otherwise "black". Press Enter to "send".

How do I make a hover effect with JavaScript events?

"mouseenter" fires when the pointer moves onto an element. "mouseleave" fires when it moves off.

Pair them to switch a class on and off, like the Diwali lamps in Lesson 4. On a phone there is no hover, so tap events ("click") are often added too.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Diyas ready: 3

🤔 Predict the output

Think like JavaScript: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

const btn = document.createElement("button");
let count = 0;
btn.addEventListener("click", () => {
  count = count + 1;
});
btn.click();
btn.click();
btn.click();
console.log(count);

Question 2. What does this print?

const btn = document.createElement("button");
console.log("A");
btn.addEventListener("click", () => console.log("B"));
console.log("C");
btn.click();

Question 3. What does this print?

const btn = document.createElement("button");
btn.textContent = "Like";
btn.addEventListener("click", (e) => {
  console.log(e.type, e.target.textContent);
});
btn.click();

🧩 Your challenge

Build a like button for a class photo. Each click toggles between liked and not liked: the button text changes between "🤍 Like" and "❤️ Liked", and the likes number goes up by 1 or down by 1. The photo starts with 12 likes. When the page loads, log the start text. Expected console output on load: Likes: 12 (and after one click: Likes: 13)

Expected output in the console:
Likes: 12
🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it

⚠️ Common mistakes (and how to fix them)

❌ Wrong

function sayHi() {
  console.log("Hi!");
}
document.querySelector("#hi").addEventListener("click", sayHi());

No error, but "Hi!" prints at once when the page loads, and clicking does nothing. sayHi() runs the function right away and passes its result (undefined).

✅ Right

function sayHi() {
  console.log("Hi!");
}
document.querySelector("#hi").addEventListener("click", sayHi);

Pass the function itself, without ( ): addEventListener("click", sayHi).

❌ Wrong

const go = document.querySelector("#go");
go.addEventListener("onclick", () => console.log("Going!"));
console.log("Ready");

No error, but clicking never prints "Going!". There is no event called "onclick", so the handler waits forever.

✅ Right

const go = document.querySelector("#go");
go.addEventListener("click", () => console.log("Going!"));
console.log("Ready");

Event names in addEventListener have no "on": "click", "input", "keydown".

❌ Wrong

const ok = document.querySelector("#ok");
ok.addEventlistener("click", () => console.log("OK!"));

TypeError: ok.addEventlistener is not a function

✅ Right

const ok = document.querySelector("#ok");
ok.addEventListener("click", () => console.log("OK!"));
console.log("Listener added");

Method names are case-sensitive. It is addEventListener with a capital L.

📌 Remember

  • An event is something that happens on the page: click, input, keydown, mouseenter…
  • element.addEventListener("click", handler) saves the handler; the browser calls it later.
  • Pass the function itself (sayHi), not its result (sayHi()).
  • The event object tells you details: event.type, event.target, event.key.
  • A let variable outside the handler remembers values between events, like a counter.

Finished the quiz and the challenge?

Questions students ask

What is addEventListener in JavaScript?

It is a method that connects an event to a function. element.addEventListener("click", fn) means "run fn whenever this element is clicked". You can add many listeners to the same element.

What is the difference between onclick and addEventListener?

onclick is an older way that allows only one handler per element, and a new one replaces the old. addEventListener can add many handlers and keeps HTML and JavaScript separate, so it is preferred.

What is the difference between the input and change events?

"input" fires on every keystroke while the text changes. "change" fires only when the user finishes, for example when the box loses focus. Use input for live counters.

What are the most common JavaScript events?

click, input, change, keydown, submit (for forms, Lesson 12), mouseenter, mouseleave and load. Click and input cover most beginner projects.