Handling Hover Events in jQuery

Handling Hover Events

Hover events can be handled using hover():

$(selector).hover(handlerIn,handlerout)

handlerIn is equivalent to mouseenter and handler out is equivalent to mouseleave

 

 Using hover()

This example highlights #target on mouseenter and sets it back to white on mouseleave.

$(‘#target’).hover(

function(){

$(this).css(‘background color’,’#00FF99’);

};

function(){

$(this).css(‘background-color’,’#FFFFFF’);

}

);

Alternate Hover Example

Another option is $(selector).hover(handlerInOut)

Fires the same handler for mouseenter and mouseleave events

Used with jQuery’s toggle methods:

$(‘p’).hover(function() {

$(this).toggleclass(‘over’);

});

This code will toggle the class applied to a paragraph element

<html>

<head>

<style type=”text/css”>

.Hilight{

background-color:#efefef;

}

</style>

<script type=”text/javascript” src=”jquery.js”></script>

<script type=”text/javascript”>

$(document).ready(function() {

/*

$(“table#MyTable tr”).hover(

function(){

//mouseenter

$(this).css(“background-color”,”#efefef”);

};

function(){

//mouseleave

$(this).css(“background-color”,”#ffffff”);

}

};

*/

$(“table#Mytable tr”).hover(function() {

$(this).toggleclass(“Hilight”);

}};

});

</script>

</head>

<body>

<table id=”MyTable” border=”1”>

<tr>

<th>ENO</th>

<th>Name</th>

<th>Sal</th>

</tr>

<tr>

<td>1001</td>

<td>sekhar1</td>

<td>459.09</td>

</tr>

<tr>

<td>1002</td>

<td>sekhar2</td>

<td>459.09</td>

</tr>

<tr>

<td>1003</td>

<td>sekhar3</td>

<td>459.09</td>

</tr>

<tr>

<td>1004</td>

<td>sekhar4</td>

<td>459.09</td>

</tr>

<tr>

<td>1005</td>

<td>sekhar5</td>

<td>459.09</td>

</tr>

</table>

</body>

</html>

<html>

<head>

<style type=”text/css”>

.Hilight{

background-color:#efefef;

}

</style>

<script type=”text/javascript” src=”jquery.js”></script>

<script type=”text/javascript”>

$(document).ready(function() {

$(“table#MyTable tr”).toggle(

function(){

//click

$(this).css(“background-color”,”#efefef”);

};

function(){

//click

$(this).css(“background-color”,”purple”);

};

function(){

//click

$(this).css(“background-color”,”yellow”);

};

function() {

//click

$(this).css(“background-color”,”pink”);

}

};

}};

</script>

</head>

<body>

<table id=”MyTable” border=”1”>

<tr>

<th>ENO</th>

<th>Name</th>

<th>Sal</th>

</tr>

<tr>

<td>1001</td>

<td>sekhar1</td>

<td>459.09</td>

</tr>

<tr>

<td>1002</td>

<td>sekhar2</td>

<td>459.09</td>

</tr>

<tr>

<td>1003</td>

<td>sekhar3</td>

<td>459.09</td>

</tr>

<tr>

<td>1004</td>

<td>sekhar4</td>

<td>459.09</td>

</tr>

<tr>

<td>1005</td>

<td>sekhar5</td>

<td>459.09</td>

</tr>

</table>

</body>

</html>