jQuery for the win

I needed to toggle some text between “show help” and “hide help”.

First, I wrote this and thought I was good:

<style type="text/css">
span.hide { display:none }
</style>
<script type="text/javascript">
$(document).ready(function () {
    $("a.showhide").click(function (event) {
        $("span.show").toggle();
        $("span.hide").toggle();
        return false;
    })
});
</script>
<a class="showhide"><span class="show">Show Help</span><span class="hide">Hide Help</span></a>

That flips the text from “Show Help” to “Hide Help”. But the code can be made even shorter by calling toggle on both spans at once:

<script type="text/javascript">
$(document).ready(function () {
    $("a.showhide").click(function (event) {
        $("a.showhide span").toggle();
        return false;
    })
});
</script>

I heart jQuery.

  • http://www.just-another.net Ben

    I agree completely. I love it so much, I rewrote the monitor (the 60′ plasma on my desk) in JQuery with a CherryPy backend. Again, I loves the JQuery.

    Along the same lines as your code (the whole “greedy selector thing” if you will) it has a flippin sweet method called `each`.

    Check it out:

    
        $('img').each(
            function() {
                $(this).attr('src',$(this).attr('src'));
            }
        );
    

    Iterates through every img element and basically refreshes the src attribute.

  • http://www.just-another.net Ben

    Ew. Can you fix me formatting in the above? I seem to have mucked up the markdown. No preview button?!

  • http://tplus1.com matt

    So, that “each” will go out and grab the most recent version of that image? Neato. I can see how that would be really useful for a monitor app, since the images are dynamically generated.

    You’re a perl person — what’s MTFNPY all about?

  • http://www.just-another.net Ben

    Really…I have no idea. I’ve been out of the loop for the last year or two.

  • http://www.sinohotel.com/english/tours/guangzhou/index.html Guangzhou Tour

    That Sounds interesting, I agree with you.Please keep at your good work, I would come back often.*