jQuery on hover(), mouseenter() and mouseleave() Methods

To do something when an element is hovered over, use the jQuery hover() method and pass a function as the first argument.

 

The example below demonstrates getting the content of an element with jQuery when the user hovers over it.

 

<div id="foo">Item content</div>
$('#foo').hover((e) => {
  console.log($(e.target).text());
}, () => {});

 

Handle Mouse Enter and Mouse Leave with jQuery

The jQuery hover() method accepts two arguments, the first is to handle a mouse enter event and the second is a mouse leave event. Let's create another function to handle enter and leave mouse events on an element.

 

<div id="foo">Item content</div>
function mouseEnter(){
  console.log($(this).attr('id'));
}

function mouseLeave(){
  console.log($(this).text());
}

$('#foo').hover(mouseEnter, mouseLeave);

 

The example above passes the hover event object to two different functions on mouse enter and leave. To access the element that was hovered over, use the this property.

 

Mouse Enter only with jQuery

The jQuery hover() method handles enter and leave mouse events. If you only need to handle a mouse enter event use the mouseenter() method and pass a handler as the first argument.

 

<div id="foo">Item content</div>
$('#foo').mouseenter(function () {
  console.log($(this).attr('id'));
});

 

Mouse Leave only with jQuery

To deal with mouse leave events only, use the mouseleave() method and pass a handler as the first argument.

 

<div id="foo">Item content</div>
$('#foo').mouseleave(function () {
  console.log($(this).attr('id'));
});
jquery