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 onmouseenter event only fires when entering the target element
  • It doesn't bubble up through parent elements
  • Often paired with onmouseleave for complete hover interactions
  • More predictable than onmouseover for 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.

Updated on: 2026-03-15T23:18:59+05:30

365 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements