DEV Community

Mohamed Idris
Mohamed Idris

Posted on

Understanding Mouse Movement Events in JavaScript

onMouseEnter:
This event is triggered when the mouse cursor enters the target element. It is commonly used to trigger actions when the user hovers over an element.

onMouseOver:
This event is triggered when the mouse cursor moves over the target element or any of its child elements. It can be used to track mouse movement within an element and trigger actions accordingly.

onMouseLeave:
This event is triggered when the mouse cursor leaves the target element. It is useful for triggering actions when the user stops hovering over an element.

Credits: John Smilga's react course

Top comments (2)

Collapse
 
edriso profile image
Mohamed Idris

onMouseEnter:
This event is triggered when the mouse cursor enters the target element. It is commonly used to trigger actions when the user hovers over an element.

// Example: Change background color on hover
element.onmouseenter = function() {
  element.style.backgroundColor = 'yellow';
};
Enter fullscreen mode Exit fullscreen mode

onMouseOver:
This event is triggered when the mouse cursor moves over the target element or any of its child elements. It can be used to track mouse movement within an element and trigger actions accordingly.

// Example: Log mouse position over an element
element.onmouseover = function(event) {
  console.log(`Mouse position: ${event.clientX}, ${event.clientY}`);
};
Enter fullscreen mode Exit fullscreen mode

onMouseLeave:
This event is triggered when the mouse cursor leaves the target element. It is useful for triggering actions when the user stops hovering over an element.

// Example: Reset background color when mouse leaves
element.onmouseleave = function() {
  element.style.backgroundColor = '';
};
Enter fullscreen mode Exit fullscreen mode