English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

jQuery hover() method

jQuery Events

When the mouse pointer hovers over the selected element, the hover() method specifies two functions to be executed.

This method triggersmouseenterandmouseleaveevent.

Calling the hover() method is a shorthand: $(selector).mouseenter(function_in).mouseleave(function_out)

Note:When a single function is passed, the hover() method executes the function for both mouseenter and mouseleave events.

Syntax:

$(selector).hover(function_in, function_out)

Example

Change the background color of all <p> elements when the mouse pointer hovers over them:

$("p").hover(function(){
  $(this).css("background-color", "yellow");
  }, function(){
  $(this).css("background-color", "lightblue");
});
Test and see‹/›

Add special styles to list items to be hovered over:

$(document).ready(function(){
  $("li").hover(function(){funcIn(this);}, function(){funcOut(this);});
});
function funcIn(x) {
  $(x).html("Mouse<b>ENTER</b> Pressed event triggered");
  $(x).css("background", "yellow");
}
function funcOut(x) {}}
  $(x).html("Trigger mouse leave event");
  $(x).css("background", "white");
}
Test and see‹/›

If only one function is specified, the function will be executed for both mouseenter and mouseleave events at the same time:

$("div").hover(function(){
  $(this).css("background", randColor());
});
// Random Color Function
function randColor() {
  return 'rgb(' + Math.floor(Math.random()*256) + ',' + Math.floor(Math.random()*256) + 
  ',' + Math.floor(Math.random()*256) + ')';
}
Test and see‹/›

Parameter Value

ParameterDescription
function_inFunction executed when the mouse pointer enters the element
function_outFunction executed when the mouse pointer leaves the element (optional)

jQuery Events