JQuery: common “event pairs” helpers
There are certain scenarios where you handle events in “pairs”. For instance, I guess we’ve all written JavaScript code for handling mouse over and mouse out events (which, btw, is also commonly known as hovering). Take a look at the following snippet:
<div>
Mouse over turns green! Mouse out turns black...
</div>
<script type="text/javascript">
$(function() {
$("div").bind("mouseover", function() {
$(this).css("color", "green");
});
$("div").bind("mouseout", function() {
$(this).css("color", "black");
});
});
</script>
If you run the previous sample, you’ll see that putting the mouse cursor over will result in changing the div’s text color to green and removing it will turn it back to black. JQuery simplifies the code we need to write in these scenarios by introducing the hover method. Here’s how the code would look if we used that method:
<script type="text/javascript">
$(function() {
$("div").hover(
function() { $(this).css("color", "green"); },
function() { $(this).css("color", "black");});
});
</script>
The hover method expects two parameters: the first function will be invoked when the mouse enters the target and the second will be called when the cursor leaves that target.
Besides this helper, there’s also the toggle method. This method receives two or more functions and will call each function one at a time for each click done over any of the container’s wrapped set elements. The next snippet keeps changing the text color of all divs for each click:
$(function() {
$("div").toggle(
function() { $(this).css("color", "green"); },
function() { $(this).css("color", "red"); },
function() { $(this).css("color", "blue"); },
function() { $(this).css("color", "black");});
});
Notice that there are no restrictions to the number of functions you can pass to the toggle method (and you’ll typically pass at least two when using this method.
And that’s all for now. Keep tuned for more on JQuery.