Skip to main content

Mouse Events in JavaScript (Live Playground)

In this tutorial, we'll explore how to work with mouse events in JavaScript to create interactive web applications that respond to user inputs, such as clicks, double-clicks, mouse movement, and more.

Common mouse events

Here are some common mouse events you might encounter when working with JavaScript:

  • click: Triggered when a user clicks on an element.
  • dblclick: Triggered when a user double-clicks on an element.
  • mousedown: Triggered when a user presses a mouse button down on an element.
  • mouseup: Triggered when a user releases a mouse button on an element.
  • mousemove: Triggered when the mouse pointer is moved over an element.
  • mouseover: Triggered when the mouse pointer is moved onto an element.
  • mouseout: Triggered when the mouse pointer is moved out of an element.

Handling mouse events

To handle mouse events in JavaScript, you can use the addEventListener() method. Here's an example of how to handle the click event:

<!DOCTYPE html>
<html>
<head>
<title>Mouse Events Example</title>
</head>
<body>
<button id="myButton">Click me!</button>

<script>
// Get a reference to the button element
var button = document.getElementById('myButton');

// Function to handle the click event
function handleClick() {
console.log('Button clicked!');
}

// Add a click event listener to the button
button.addEventListener('click', handleClick);
</script>
</body>
</html>

In this example, we define a handleClick() function that will be executed when the button is clicked. We then use the addEventListener() method to register the handleClick() function as a callback for the click event on the button.

Example: Changing the background color on mouseover

Now let's create an example where we change the background color of an element when the mouse pointer is moved over it:

<!DOCTYPE html>
<html>
<head>
<title>Mouseover Example</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div class="box" id="myBox"></div>

<script>
// Get a reference to the box element
var box = document.getElementById('myBox');

// Function to handle the mouseover event
function handleMouseover() {
box.style.backgroundColor = 'blue';
}

// Add a mouseover event listener to the box
box.addEventListener('mouseover', handleMouseover);
</script>
</body>
</html>

In this example, we define a handleMouseover() function that changes the background color of the box element to blue when the mouse pointer is moved over it. We then use the addEventListener() method to register the handleMouseover() function as a callback for the mouseover event on the box.

Live Playground, Try it Yourself