jQuery hover() method is a combination of mouseenter() and mouseleave() methods. The hover() method attaches an html element to two of the event handler functions, the first event handler function executes when the mouse pointer enters the html element and the second event handler function executes when mouse pointer leaves the html element.
jQuery hover() method Syntax
$(selector).hover(function(){ //this code will execute when mouse enters the html element }, function(){ //this code will execute when mouse leaves the html element });
Here $(selector) is a jQuery selector that selects html elements that are attached to event handler functions by hover() method.
jQuery hover() Example
In the following example we have two paragraphs, we want to perform hover event on the first paragraph so we have assigned an id to the first paragraph and attached this paragraph with event handler functions using hover() method.
There are two event handler functions here, the first function executes when the mouse enters attached html element and the second event handler function executes when the mouse leaves the attached html element.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("#para").hover(function(){ $(this).animate({fontSize: '3em'}, "slow"); }, function(){ $(this).hide(); }); }); </script> </head> <body> <h2>jQuery hover event example</h2> <p id="para">This example is published on beginnersbook.com.</p> <p>When the mouse pointer enters the first paragraph, the font size of the paragraph will be increased but when mouse pointer leaves the paragraph, the paragraph will be hidden.</p> </body> </html>
Output:
When the page is initially loaded and no action is performed:
This screenshot is taken when we have not performed any action on the page, the page is just loaded in the browser.
When mouse pointer enters the first paragraph (with id “para”):
This screenshot is taken after the mouse enters the paragraph with id “para”, as you can see the font size of the paragraph is increased because in the first event handler function we are increasing the font size using animate() method.
When mouse pointer leaves the first paragraph (with id “para”):
This screenshot is taken after the mouse leaves the paragraph with id “para”, as you can see that the paragraph is disappeared because we have hidden the paragraph in the second event handler function using hide() method.
Leave a Reply