Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is onmouseenter event in JavaScript?
The onmouseenter event triggers when the mouse pointer enters an HTML element. Unlike onmouseover, it doesn't bubble and only fires when entering the target element itself, not its child elements.
Syntax
element.onmouseenter = function() {
// Code to execute
};
// Or in HTML
<element onmouseenter="functionName()"></element>
Example: Basic Mouse Enter Event
Here's how to use the onmouseenter event to display an alert when hovering over text:
<html>
<head>
<script>
function sayHello() {
alert("Mouse entered the element!");
}
</script>
</head>
<body>
<p onmouseenter="sayHello()" style="padding: 20px; background-color: lightblue;">
Hover over this text to trigger the event
</p>
</body>
</html>
Example: Dynamic Styling with Mouse Enter
A more practical example that changes element styling when the mouse enters:
<html>
<head>
<script>
function changeStyle(element) {
element.style.backgroundColor = "yellow";
element.style.fontSize = "18px";
}
function resetStyle(element) {
element.style.backgroundColor = "lightgray";
element.style.fontSize = "14px";
}
</script>
</head>
<body>
<div onmouseenter="changeStyle(this)"
onmouseleave="resetStyle(this)"
style="padding: 20px; background-color: lightgray; cursor: pointer;">
Hover to see style changes
</div>
</body>
</html>
onmouseenter vs onmouseover
| Property | onmouseenter | onmouseover |
|---|---|---|
| Bubbling | No | Yes |
| Triggers on child elements | No | Yes |
| Best for | Simple hover effects | Complex nested interactions |
Key Points
- The
onmouseenterevent only fires when entering the target element - It doesn't bubble up through parent elements
- Often paired with
onmouseleavefor complete hover interactions - More predictable than
onmouseoverfor simple hover effects
Conclusion
The onmouseenter event provides precise control for mouse hover interactions without the complexity of event bubbling. Use it for clean, predictable hover effects on specific elements.
Advertisements
