Mouse moving events: mouseover and mouseout
mouseover: The mouseover events occurs when a mouse pointer comes over to the targeted element.
mouseout: The mouseout events occurs when mouse pointer leave the targeted element.
Both mouseover and mouseout event object have the target and relatedTarget properties.
mouseover event object:
event.target: It returns the element that mouse came over.
event.relatedTarget: It returns the element from where the mouse came.
mouseout event object:
event.target: It returns the element that mouse left.
event.relatedTarget: It returns the element in which mouse came over to the new element.
Note:
event.relatedTarget property can be the null.
It is happen because the mouse can be came to the element from the out of window.
Example:
element1.onmouseover = function (event) { var string = "mouseover [" + "Target: " + event.target.id + "] [" + "relatedTarget: " + event.relatedTarget.id + "]\n"; mouseStatus.value += string; }; element1.onmouseout = function (event) { var string = "mouseout [" + "Target: " + event.target.id + "] [" + "relatedTarget:" + event.relatedTarget.id + "]\n"; mouseStatus.value += string; };
mouseout event occurs on child element
When mouse pointer entered to an element than the mouseover event will be occurred. When mouse pointer goes to the child element than the mouseout event will be occurred of the parent element. The cursor is still in the element but we have the mouseout event from it.
The mouse cursor may be only over a single element at any time, it is the most nested one.
Example:
element1.onmouseover = function (event) { var string = "mouseover [" + "Target: " + event.target.id + "] [" + "relatedTarget: " + event.relatedTarget.id + "]\n"; mouseStatus.value += string; }; element1.onmouseout = function (event) { var string = "mouseout [" + "Target: " + event.target.id + "] [" + "relatedTarget:" + event.relatedTarget.id + "]\n"; mouseStatus.value += string; };
mouseout-on-child-element live demo
- When mouse pointer entered to the red parent element than the mouseover [Target: red] event will be occured of the parent element.
- When mouse pointer moves to the blue child element than the mouseout [Target: red] event will be occured of the parent element.
- After it immediately mouseover [Target: blue] event will be occured of the child element.
So it can be occurred the abnormally behaviour of the program.
We can fix this problem by using the mouseenter/mouseleave event.