How to use Event Listener In Javascript
In this approach, we are using JavaScript event listeners (onmouseout and onmouseover) to trigger functions when the mouse moves in and out of the button. The functions change the button’s background color and text content dynamically for interactive user feedback.
Example: The below example uses JavaScript Event Listener to call a JavaScript function from an onmouseout event.
<!DOCTYPE html>
<html>
<head>
<title>Using JavaScript Event Listener</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
font-family: Arial, sans-serif;
}
#container {
text-align: center;
}
#myButton {
transition: background-color 0.3s ease;
cursor: pointer;
}
</style>
</head>
<body>
<div id="container">
<h1>
Using JavaScript Event Listener
</h1>
<button id="myButton">
Hover over me!
</button>
</div>
<script>
document.getElementById("myButton").onmouseout = function () {
let button = document.getElementById("myButton");
button.style.backgroundColor = "blue";
button.innerText = "Mouse moved away!";
};
document.getElementById("myButton").onmouseover = function () {
let button = document.getElementById("myButton");
button.style.backgroundColor = "red";
button.innerText = "Hover over me!";
};
</script>
</body>
</html>
Output:
How to Call a JavaScript Function from an onmouseout Event ?
The onmouseout event in JavaScript triggers when the mouse pointer leaves an element. This event is commonly used in web development to execute certain functions when a user moves the mouse away from a specific area on the webpage.
Below are the approaches to call a JavaScript function from an onmouseout event:
Table of Content
- Using inline event handler in HTML
- Using JavaScript Event Listener