Introductions
Mouse and keyboard events help JavaScript respond to actions performed by users. Mouse events include clicking, double-clicking, moving, entering, and leaving elements. Keyboard events allow JavaScript to detect keys being pressed or released. These events are important for creating interactive menus, games, forms, shortcuts, and user-friendly webpages. JavaScript Mouse and Keyboard Events practice questions with solutions help to understand the concepts.
Question 1: Detect a Mouse Click
Problem
Create a button and display a message when the user clicks it.
Solution
<button id="clickButton">Click Me</button>
<p id="message"></p>
<script>
const button = document.getElementById("clickButton");
const message = document.getElementById("message");
button.addEventListener("click", function() {
message.textContent = "You clicked the button!";
});
</script>
Output
Before clicking:
[Click Me]
After clicking:
[Click Me]
You clicked the button!
Step-by-step Explanation
- JavaScript selects the button.
- JavaScript selects the paragraph.
clickdetects a mouse click.- The function runs when the button is clicked.
textContentdisplays the message.
Question 2: Detect a Double Click
Problem
Create a box that changes its text when the user double-clicks it.
Solution
<div id="box">Double-click this box</div>
<script>
const box = document.getElementById("box");
box.style.padding = "20px";
box.style.border = "1px solid black";
box.addEventListener("dblclick", function() {
box.textContent = "You double-clicked the box!";
});
</script>
Output
Before double-clicking:
Double-click this box
After double-clicking:
You double-clicked the box!
Step-by-step Explanation
- The box is selected using its ID.
dblclicklistens for a double-click.- When the user double-clicks, the function executes.
- The box text is changed using
textContent.
Question 3: Detect Mouse Enter and Mouse Leave
Problem
Create a box that changes its background color when the mouse enters and returns to its original color when the mouse leaves.
Solution
<div id="box">Move your mouse here</div>
<script>
const box = document.getElementById("box");
box.style.padding = "20px";
box.style.backgroundColor = "lightgray";
box.addEventListener("mouseenter", function() {
box.style.backgroundColor = "lightblue";
});
box.addEventListener("mouseleave", function() {
box.style.backgroundColor = "lightgray";
});
</script>
Output
Mouse enters:
Background → Light Blue
Mouse leaves:
Background → Light Gray
Step-by-step Explanation
mouseenterruns when the mouse enters the box.- The background changes to light blue.
mouseleaveruns when the mouse leaves.- The background changes back to light gray.
Question 4: Detect Mouse Movement
Problem
Display the mouse pointer’s X and Y coordinates while the user moves the mouse over a box.
Solution
<div id="box">Move your mouse inside this box</div>
<p id="coordinates"></p>
<script>
const box = document.getElementById("box");
const coordinates = document.getElementById("coordinates");
box.style.width = "300px";
box.style.height = "150px";
box.style.border = "1px solid black";
box.addEventListener("mousemove", function(event) {
coordinates.textContent =
"X: " + event.clientX + " | Y: " + event.clientY;
});
</script>
Output
As the mouse moves, the page may display:
X: 450 | Y: 280
The values change according to the mouse position.
Step-by-step Explanation
mousemoveruns whenever the mouse moves.- The browser provides an event object.
event.clientXgives the horizontal mouse position.event.clientYgives the vertical mouse position.- The coordinates are displayed dynamically.
Question 5: Detect Which Keyboard Key Was Pressed
Problem
Create an input box and display the name of the key pressed by the user.
Solution
<input id="textInput" type="text" placeholder="Press any key">
<p id="result"></p>
<script>
const input = document.getElementById("textInput");
const result = document.getElementById("result");
input.addEventListener("keydown", function(event) {
result.textContent = "You pressed: " + event.key;
});
</script>
Output
If the user presses the A key:
You pressed: a
If the user presses the Enter key:
You pressed: Enter
Step-by-step Explanation
- JavaScript selects the input.
keydowndetects a key press.event.keyidentifies the key.- The key name is displayed inside the paragraph.
Question 6: Detect the Enter Key
Problem
Create an input field. When the user presses Enter, display a message.
Solution
<input id="nameInput" type="text" placeholder="Enter your name">
<p id="message"></p>
<script>
const input = document.getElementById("nameInput");
const message = document.getElementById("message");
input.addEventListener("keydown", function(event) {
if (event.key === "Enter") {
message.textContent = "You pressed Enter!";
}
});
</script>
Output
When the user presses Enter:
You pressed Enter!
Step-by-step Explanation
- The
keydownevent detects keyboard presses. event.keytells us which key was pressed.- The
ifstatement checks whether the key is"Enter". - If true, the message is displayed.
Question 7: Create a Keyboard Shortcut
Problem
Create a keyboard shortcut that displays a message when the user presses Ctrl + S.
Solution
<p id="message">Press Ctrl + S</p>
<script>
const message = document.getElementById("message");
document.addEventListener("keydown", function(event) {
if (event.ctrlKey && event.key.toLowerCase() === "s") {
event.preventDefault();
message.textContent = "Ctrl + S was pressed!";
}
});
</script>
Output
When the user presses:
Ctrl + S
The page displays:
Ctrl + S was pressed!
Step-by-step Explanation
- The
keydownevent listens for keyboard presses. event.ctrlKeychecks whether Ctrl is being held.event.keyidentifies the pressed key.toLowerCase()makes the comparison easier.- Both conditions must be true.
preventDefault()prevents the browser’s normal save action.- The custom message is displayed.
Question 8: Detect the Shift Key
Problem
Create an input box and display a message when the user presses a key while holding the Shift key.
Solution
<input id="inputBox" type="text" placeholder="Hold Shift and press a key">
<p id="message"></p>
<script>
const input = document.getElementById("inputBox");
const message = document.getElementById("message");
input.addEventListener("keydown", function(event) {
if (event.shiftKey) {
message.textContent = "Shift key is being pressed!";
}
});
</script>
Output
When the user holds Shift and presses a key:
Shift key is being pressed!
Step-by-step Explanation
keydowndetects the keyboard action.event.shiftKeychecks whether Shift is being held.- If it is true, the message is displayed.
- This technique can be used for keyboard shortcuts.
Question 9: Count Mouse Clicks
Problem
Create a button that counts how many times the user clicks it.
Solution
<button id="clickButton">Click Me</button>
<p id="count">Clicks: 0</p>
<script>
const button = document.getElementById("clickButton");
const countText = document.getElementById("count");
let count = 0;
button.addEventListener("click", function() {
count++;
countText.textContent = "Clicks: " + count;
});
</script>
Output
After one click:
Clicks: 1
After three clicks:
Clicks: 3
Step-by-step Explanation
countstarts at0.- The button listens for a click.
- Every click increases
countby1. - The updated value is displayed.
- The variable remembers the number of clicks.
Question 10: Build a Simple Mouse and Keyboard Interaction
Problem
Create a box that:
- Changes color when the mouse enters.
- Returns to normal when the mouse leaves.
- Displays the last keyboard key pressed when the user types inside an input.
Solution
<div id="box">Move your mouse over me</div>
<input id="inputBox" type="text" placeholder="Press any key">
<p id="keyMessage"></p>
<script>
const box = document.getElementById("box");
const input = document.getElementById("inputBox");
const keyMessage = document.getElementById("keyMessage");
box.style.width = "300px";
box.style.padding = "30px";
box.style.backgroundColor = "lightgray";
box.addEventListener("mouseenter", function() {
box.style.backgroundColor = "lightgreen";
});
box.addEventListener("mouseleave", function() {
box.style.backgroundColor = "lightgray";
});
input.addEventListener("keydown", function(event) {
keyMessage.textContent = "Last key: " + event.key;
});
</script>
Output
When the mouse enters the box:
Box background → Light Green
When the mouse leaves:
Box background → Light Gray
If the user presses A:
Last key: a
If the user presses Enter:
Last key: Enter
Step-by-step Explanation
- JavaScript selects the box.
- JavaScript selects the input.
- JavaScript selects the message paragraph.
mouseenterchanges the box color.mouseleaverestores the original color.keydowndetects keyboard presses.event.keyidentifies the pressed key.- The key is displayed dynamically.
- This example combines mouse and keyboard events in one webpage.
Key Takeaways
- Mouse events respond to mouse actions.
- Keyboard events respond to keyboard actions.
clickdetects a mouse click.dblclickdetects a double-click.mouseenterdetects when the pointer enters an element.mouseleavedetects when the pointer leaves an element.mousemovedetects mouse movement.keydowndetects a keyboard key being pressed.keyupdetects when a key is released.event.keytells you which keyboard key was involved.event.ctrlKeychecks whether Ctrl is pressed.event.shiftKeychecks whether Shift is pressed.event.altKeychecks whether Alt is pressed.event.preventDefault()can stop a browser’s default action.- Mouse and keyboard events are essential for interactive websites.
FAQs
1. What are mouse events in JavaScript?
Mouse events are events triggered by mouse actions.
Common examples include:
click
dblclick
mouseenter
mouseleave
mousemove
mousedown
mouseup
2. What are keyboard events in JavaScript?
Keyboard events occur when users interact with the keyboard.
The most common ones are:
keydown
keyup
For example:
document.addEventListener("keydown", function(event) {
console.log(event.key);
});
3. What is the difference between keydown and keyup?
keydown occurs when a key is pressed.
keyup occurs when the key is released.
document.addEventListener("keyup", function(event) {
console.log("Key released:", event.key);
});
4. How can I detect the Enter key?
Use event.key.
document.addEventListener("keydown", function(event) {
if (event.key === "Enter") {
console.log("Enter pressed");
}
});
5. How can I detect Ctrl, Shift, or Alt?
JavaScript provides special properties on the event object.
event.ctrlKey
event.shiftKey
event.altKey
Example:
document.addEventListener("keydown", function(event) {
if (event.ctrlKey && event.key === "s") {
console.log("Ctrl + S");
}
});
6. What is mousemove used for?
mousemove runs whenever the mouse pointer moves over an element.
It can be used for:
- Drawing applications
- Games
- Mouse coordinates
- Interactive animations
- Custom cursors
- Image effects
7. Can JavaScript handle mouse and keyboard events at the same time?
Yes. You can attach different event listeners to different elements or even the same element.
button.addEventListener("click", handleClick);
input.addEventListener("keydown", handleKeyDown);
This allows a webpage to respond to many types of user interaction.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
