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.
Ben said,
March 7, 2008 @ 8:25 pm
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.
Ben said,
March 7, 2008 @ 8:27 pm
Ew. Can you fix me formatting in the above? I seem to have mucked up the markdown. No preview button?!
matt said,
March 7, 2008 @ 8:41 pm
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?
Ben said,
March 28, 2008 @ 11:13 am
Really…I have no idea. I’ve been out of the loop for the last year or two.