JavaScript Mouse and Keyboard Events Practice Questions with Solutions

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

  1. JavaScript selects the button.
  2. JavaScript selects the paragraph.
  3. click detects a mouse click.
  4. The function runs when the button is clicked.
  5. textContent displays 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

  1. The box is selected using its ID.
  2. dblclick listens for a double-click.
  3. When the user double-clicks, the function executes.
  4. 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

  1. mouseenter runs when the mouse enters the box.
  2. The background changes to light blue.
  3. mouseleave runs when the mouse leaves.
  4. 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

  1. mousemove runs whenever the mouse moves.
  2. The browser provides an event object.
  3. event.clientX gives the horizontal mouse position.
  4. event.clientY gives the vertical mouse position.
  5. 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

  1. JavaScript selects the input.
  2. keydown detects a key press.
  3. event.key identifies the key.
  4. 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

  1. The keydown event detects keyboard presses.
  2. event.key tells us which key was pressed.
  3. The if statement checks whether the key is "Enter".
  4. 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

  1. The keydown event listens for keyboard presses.
  2. event.ctrlKey checks whether Ctrl is being held.
  3. event.key identifies the pressed key.
  4. toLowerCase() makes the comparison easier.
  5. Both conditions must be true.
  6. preventDefault() prevents the browser’s normal save action.
  7. 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

  1. keydown detects the keyboard action.
  2. event.shiftKey checks whether Shift is being held.
  3. If it is true, the message is displayed.
  4. 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

  1. count starts at 0.
  2. The button listens for a click.
  3. Every click increases count by 1.
  4. The updated value is displayed.
  5. 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

  1. JavaScript selects the box.
  2. JavaScript selects the input.
  3. JavaScript selects the message paragraph.
  4. mouseenter changes the box color.
  5. mouseleave restores the original color.
  6. keydown detects keyboard presses.
  7. event.key identifies the pressed key.
  8. The key is displayed dynamically.
  9. This example combines mouse and keyboard events in one webpage.

Key Takeaways

  • Mouse events respond to mouse actions.
  • Keyboard events respond to keyboard actions.
  • click detects a mouse click.
  • dblclick detects a double-click.
  • mouseenter detects when the pointer enters an element.
  • mouseleave detects when the pointer leaves an element.
  • mousemove detects mouse movement.
  • keydown detects a keyboard key being pressed.
  • keyup detects when a key is released.
  • event.key tells you which keyboard key was involved.
  • event.ctrlKey checks whether Ctrl is pressed.
  • event.shiftKey checks whether Shift is pressed.
  • event.altKey checks 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.

Scroll to Top