jQuery supports a variety of mouse related events. In this article, we will take a closer look at other events such as hover, mousedown, mouseup, mouseenter, mouseleave, mousemove, mouseover, and mouseout.
Syntax
$(selector).hover(inFunction,outFunction) $(selector).mousedown(function) $(selector).mouseup(function) $(selector).mouseenter(function) $(selector).mouseleave(function) $(selector).mouseover(function) $(selector).mouseout(function) $(selector).mousemove(function)
HTML Example
We will use the following HTML for the examples listed below.
Hover
The hover event will bind two handlers to the matched elements, to be executed when the mouse pointer enters (mouseenter) and leaves (mouseleave) the elements. The syntax for the hover event is $(selector).hover(inFunction,outFunction). Here is an example.
Mousedown and Mouseup
The mousedown event will trigger as soon as the mouse button is pressed. Unlike the click event, it does not wait for the button to be depressed. This event can be used in place of the click event when you want to have the event fire as soon as the button is pressed.
This event remains triggered while the button is clicked and held. The syntax for the mousedown event is $(selector).mousedown(function). The mouseup event will trigger as soon as the mouse button is released. The syntax for the mouseup event is $(selector).mouseup(function). Here is an example.
Mouseover, Mouseout, Mouseenter, and Mouseleave
Mouseover is generally combined with mouseout while mouseenter is usually combined with mouseleave. The mouseover and mouseenter, and, mouseout and mouseleave events are similar but do have specific differences.
In the case of mouseenter and mouseleave, the events trigger when the pointer moves in and out of the bound element. The mouseover and mouseout events trigger as well when the pointer moves out of any child element within the bound element.
In the example below, the mouseenter and mouseleave events are triggered on the left div element, while the mouseover and mouseout events are triggered on the right div.
You will notice that when you mouseover and mouseout over a child element (span) in the right div, the counter increases as well. Where in the left div, this behaviour does not occur.
Mousemove
The mousemove event occurs whenever the mouse pointer moves within a specified element. The mousemove() method triggers the mousemove event, or if the function parameter is set, it specifies what happens when a mousemove event occurs. Here is an example.