What is the hover() method in jQuery?

The j Query library has numerous methods. One of them is the hover() method, which triggers events on some mouse actions.

The hover() method

This method is called when a mouse cursor hovers over an element. With this method, we can bind some actions to two events. These events are:

  • mouseenter
  • mouseleave

mouseenter

Events are triggered when we bring the cursor over the element.

mouseleave

Events are triggered when we remove the cursor from the element.

Syntax

$( selector ).hover( handlerIn, handlerOut )

Parameter

This function will accept two parameters which include:

  • selector : This is the element’s selector to be captured.

  • handlerIn : This function handles what will happen to the element when the mouse enters the element.

  • handlerOut : (optional) This function handles what will happen to the element when the mouse leaves the element.

If one parameter is provided to the function, what is specified in the handleIn function will be used for both the mouseenter and mouseleave events.

Explanation

In the code above, we import the jQuery library, which enables the use of the jQuery syntax. If the mouse hovers on the element, it changes the element color to green. When the mouse leaves the element, it changes to red.

Free Resources