Introductions
JavaScript events allow a webpage to respond to user actions such as clicks, typing, mouse movement, form submission, and keyboard presses. The addEventListener() method is one of the most important tools for handling these events. In this chapter, you will practice common JavaScript Events and Event Listeners practice questions with solutions from beginner to practical examples.
Question 1: Handle a Button Click
Problem
Create a button and display a message when the user clicks it.
Solution
<button id="clickButton">Click Me</button>
<script>
const button = document.getElementById("clickButton");
button.addEventListener("click", function() {
console.log("Button clicked!");
});
</script>
Output
When the button is clicked:
Button clicked!
Step-by-step Explanation
- JavaScript selects the button using its ID.
addEventListener()attaches an event listener."click"specifies the event to watch.- The function runs when the button is clicked.
- The message is displayed in the browser console.
Question 2: Change Text When a Button Is Clicked
Problem
Create a paragraph and button. Change the paragraph text when the button is clicked.
Solution
<p id="message">Click the button to change this text.</p>
<button id="changeButton">Change Text</button>
<script>
const message = document.getElementById("message");
const button = document.getElementById("changeButton");
button.addEventListener("click", function() {
message.textContent = "The text has been changed!";
});
</script>
Output
Before clicking:
Click the button to change this text.
[Change Text]
After clicking:
The text has been changed!
[Change Text]
Step-by-step Explanation
- JavaScript selects the paragraph.
- JavaScript selects the button.
- A
clickevent listener is attached. - When the button is clicked, the function runs.
textContentchanges the paragraph.
Question 3: Handle a Mouseover Event
Problem
Create a box that changes its background color when the mouse moves over it.
Solution
<div id="box">Move your mouse here</div>
<script>
const box = document.getElementById("box");
box.style.padding = "20px";
box.style.border = "1px solid black";
box.addEventListener("mouseover", function() {
box.style.backgroundColor = "lightblue";
});
</script>
Output
When the mouse moves over the box, its background changes.
Step-by-step Explanation
- The box is selected.
mouseoverdetects when the mouse pointer moves onto the element.- The event listener runs.
backgroundColorchanges to light blue.- The visual appearance changes immediately.
Question 4: Handle a Mouseout Event
Problem
Create a box that changes color when the mouse enters it and returns to its original color when the mouse leaves.
Solution
<div id="box">Move your mouse over me</div>
<script>
const box = document.getElementById("box");
box.style.padding = "20px";
box.style.backgroundColor = "lightgray";
box.addEventListener("mouseover", function() {
box.style.backgroundColor = "lightgreen";
});
box.addEventListener("mouseout", function() {
box.style.backgroundColor = "lightgray";
});
</script>
Output
- Mouse enters → light green
- Mouse leaves → light gray
Step-by-step Explanation
- The box starts with a light gray background.
mouseoverdetects the mouse entering the element.- The background changes to light green.
mouseoutdetects the mouse leaving the element.- The background changes back to light gray.
Question 5: Handle Keyboard Input with keydown
Problem
Create an input box and display the key pressed by the user.
Solution
<input id="nameInput" type="text" placeholder="Type something">
<script>
const input = document.getElementById("nameInput");
input.addEventListener("keydown", function(event) {
console.log("Key pressed:", event.key);
});
</script>
Output
If the user types:
JavaScript
The console receives keyboard events for the keys being pressed.
Step-by-step Explanation
- JavaScript selects the input.
keydownruns when a key is pressed.- The event object is stored in
event. event.keytells you which key was pressed.- The key information is displayed in the console.
Question 6: Handle Input Using the input Event
Problem
Create an input field and display its current value inside a paragraph while the user types.
Solution
<input id="nameInput" type="text" placeholder="Enter your name">
<p id="output"></p>
<script>
const input = document.getElementById("nameInput");
const output = document.getElementById("output");
input.addEventListener("input", function() {
output.textContent = "You typed: " + input.value;
});
</script>
Output
If the user types:
Rahul
The page displays:
You typed: Rahul
Step-by-step Explanation
- The input field is selected.
- The paragraph is selected.
- The
inputevent runs whenever the input value changes. input.valuegets the current value.textContentdisplays that value.
Question 7: Handle a Form Submission
Problem
Create a form and prevent the page from reloading when the user submits it.
Solution
<form id="loginForm">
<input
type="text"
id="username"
placeholder="Enter username"
>
<button type="submit">Submit</button>
</form>
<p id="message"></p>
<script>
const form = document.getElementById("loginForm");
const message = document.getElementById("message");
form.addEventListener("submit", function(event) {
event.preventDefault();
message.textContent = "Form submitted successfully!";
});
</script>
Output
After submitting:
Form submitted successfully!
Step-by-step Explanation
- JavaScript selects the form.
- A
submitevent listener is added. - When the form is submitted, the function runs.
event.preventDefault()prevents the browser’s default form submission.- The message is displayed without reloading the page.
Question 8: Use dblclick Event
Problem
Create a paragraph that changes its text when the user double-clicks it.
Solution
<p id="message">Double-click me</p>
<script>
const message = document.getElementById("message");
message.addEventListener("dblclick", function() {
message.textContent = "You double-clicked the paragraph!";
});
</script>
Output
Before double-clicking:
Double-click me
After double-clicking:
You double-clicked the paragraph!
Step-by-step Explanation
- The paragraph is selected.
dblclicklistens for a double-click.- The callback function runs after the double-click.
textContentchanges the paragraph text.
Question 9: Use change Event with a Select Box
Problem
Create a dropdown containing three courses. Display the selected course when the user changes the selection.
Solution
<select id="course">
<option value="">Select a course</option>
<option value="HTML">HTML</option>
<option value="CSS">CSS</option>
<option value="JavaScript">JavaScript</option>
</select>
<p id="result"></p>
<script>
const course = document.getElementById("course");
const result = document.getElementById("result");
course.addEventListener("change", function() {
result.textContent = "Selected course: " + course.value;
});
</script>
Output
If the user selects:
JavaScript
The page displays:
Selected course: JavaScript
Step-by-step Explanation
- The
<select>element is selected. - The paragraph is selected.
changeruns when the selected option changes.course.valuegets the selected value.- The value is displayed in the paragraph.
Question 10: Use Multiple Events Together
Problem
Create a button that changes its text and style when the mouse enters and returns to normal when the mouse leaves. When clicked, display a message.
Solution
<button id="button">Move Mouse or Click Me</button>
<p id="message"></p>
<script>
const button = document.getElementById("button");
const message = document.getElementById("message");
button.addEventListener("mouseover", function() {
button.style.backgroundColor = "green";
button.style.color = "white";
button.textContent = "Mouse Over!";
});
button.addEventListener("mouseout", function() {
button.style.backgroundColor = "";
button.style.color = "";
button.textContent = "Move Mouse or Click Me";
});
button.addEventListener("click", function() {
message.textContent = "Button was clicked!";
});
</script>
Output
When the mouse enters:
Mouse Over!
When the mouse leaves:
Move Mouse or Click Me
When the button is clicked:
Button was clicked!
Step-by-step Explanation
- JavaScript selects the button and paragraph.
- A
mouseoverlistener changes the button’s style and text. - A
mouseoutlistener restores the button. - A
clicklistener displays a message. - Multiple event listeners can be attached to the same element.
- Each listener handles a different user action.
Key Takeaways
- An event represents an action or occurrence in the browser.
- Common events include
click,mouseover,mouseout,keydown,input,change, andsubmit. addEventListener()is used to listen for events.- The first argument specifies the event type.
- The second argument is the function that runs when the event occurs.
eventcontains information about the event.event.keyidentifies a keyboard key.event.preventDefault()prevents the browser’s default action.- Multiple event listeners can be attached to one element.
- Event listeners are essential for creating interactive webpages.
FAQs
1. What is an event in JavaScript?
An event is an action or occurrence that JavaScript can detect and respond to.
Examples include:
- Button click
- Mouse movement
- Keyboard press
- Form submission
- Input changes
- Selecting an option
2. What is addEventListener()?
addEventListener() attaches a function to an event.
button.addEventListener("click", function() {
console.log("Clicked!");
});
The function runs whenever the specified event occurs.
3. What is the difference between click and dblclick?
click runs when an element is clicked.
element.addEventListener("click", function() {
console.log("Clicked");
});
dblclick runs when an element is double-clicked.
element.addEventListener("dblclick", function() {
console.log("Double clicked");
});
4. What does the input event do?
The input event runs whenever the value of an input element changes.
input.addEventListener("input", function() {
console.log(input.value);
});
It is useful for live search, character counters, and real-time form feedback.
5. What is the keydown event?
The keydown event occurs when a keyboard key is pressed.
document.addEventListener("keydown", function(event) {
console.log(event.key);
});
6. What does event.preventDefault() do?
It prevents the browser’s default behavior for an event.
For example, it can prevent a form from submitting normally:
form.addEventListener("submit", function(event) {
event.preventDefault();
});
7. Can one element have multiple event listeners?
Yes. You can attach different event listeners to the same element.
button.addEventListener("click", handleClick);
button.addEventListener("mouseover", handleMouseOver);
button.addEventListener("mouseout", handleMouseOut);
Each listener responds to its own event.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
