Event Helpers

Contact Us or call 1-877-932-8228
Event Helpers

Event Helpers

jQuery offers two event-related helper functions that can save you a few keystrokes.

$.fn.hover

The $.fn.hover method lets you pass one or two functions to be run when the mouseenter and mouseleave events occur on an element. If you pass one function, it will be run for both events; if you pass two functions, the first will run for mouseenter, and the second will run for mouseleave.

Note: Prior to jQuery 1.4, the $.fn.hover method required two functions.

$.fn.toggle

Much like $.fn.hover, the $.fn.toggle method receives two or more functions; each time a click event occurs, the next function in the list is called. Generally, $.fn.toggle is used with just two functions, but technically you can use as many as you'd like.

Note that $.fn.hover was deprecated as version 1.9, but you may still see it in legacy code.

The hover and toggle Functions

Code Sample:

jqy-events/Demos/hover-toggle.html
<html>
<head>
<style>
.hover { background-color:#CCFFCC; }
.toggle1 { color: red; }
.toggle2 { color: green; }
.toggle3 { color: blue; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> 
</head>
<body>
<ul id="myUnorderedList">
	<li><a href="http://www.webucator.com/">One</a></li>
	<li><a href="bind-event-binding.html">Two</a></li>
	<li>Three</li>
	<li>Four</li>
</ul>
<ol id="myOrderedList">
	<li><a href="http://www.webucator.com/">One</a></li>
	<li><a href="bind-event-binding.html">Two</a></li>
	<li class="clickable">Three</li>
	<li>Four</li>
</ol>
<script>

$('ul li').hover(function() { 
    $(this).toggleClass('hover'); 
});

$('ol li').hover(
	function() { 
    $(this).addClass('hover'); 
	},
	function() { 
    $(this).removeClass('hover'); 
	}
);

$('li').toggle(
	function() { 
    $(this).addClass('toggle1'); 
    $(this).removeClass('toggle2'); 
    $(this).removeClass('toggle3'); 
	},
	function() { 
    $(this).addClass('toggle2'); 
    $(this).removeClass('toggle1'); 
    $(this).removeClass('toggle3'); 
	},
	function() { 
    $(this).addClass('toggle3'); 
    $(this).removeClass('toggle2'); 
    $(this).removeClass('toggle1'); 
	},
		function() { 
    $(this).removeClass('toggle3'); 
    $(this).removeClass('toggle2'); 
    $(this).removeClass('toggle1'); 
	}
);

</script>
</body>
</html>
Next