JQuery: common “event pairs” helpers

Published Wed, Aug 5 2009 10:48

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.

Filed under:

Comments

# 9eFish said on Wednesday, August 05, 2009 8:44 PM

9efish.感谢你的文章 - Trackback from 9eFish

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above:  

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover