Mouse Events Example in JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My website</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="myBox">
Click Me 😊
</div>
<button id="myButton">Click Me</button>
<script src="script.js"></script>
</body>
</html>#myBox{
background-color: lightgreen;
width: 300px;
height: 300px;
font-size: 4.1rem;
font-weight: bold;
display: flex;
align-items: center;
text-align: center;
}
#myButton{
font-size: 3rem;
margin-top: 10px;
align-items: center;
}
const myBox = document.getElementById("myBox");
const myButton = document.getElementById("myButton");
myButton.addEventListener("click",event =>{
myBox.style.backgroundColor = "tomato";
myBox.textContent = "Ouch !!😢";
});
myButton.addEventListener("mouseover", event =>{
myBox.style.backgroundColor = "Yellow";
myBox.textContent = "Please !!😒";
})
myButton.addEventListener("mouseout",event =>{
myBox.style.backgroundColor = "lightgreen";
myBox.textContent = "Click Me 😊";
})This JavaScript code listens for mouse events on a button and changes the appearance and text of a box based on those events. Here’s a breakdown of what each event does:
Get Chamod Dilshan 😎’s stories in your inbox
Join Medium for free to get updates from this writer.
1. Click Event:
When you click the button, the box’s background color changes to tomato and its text changes to “Ouch !!😢”.
2. Mouseover Event:
When you hover the mouse over the button, the box’s background color changes to yellow and its text changes to “Please !!😒”.
3. Mouseout Event:
When you move the mouse away from the button, the box’s background color changes to light green and its text changes to “Click Me 😊”.
This setup allows the box to react dynamically to user interactions with the button, providing visual feedback and changing messages based on mouse actions.
Follow for more.









