.NET Discussion

.NET Issues, Problems, Code Samples, and Fixes

Simple jQuery Expand/Contract Functionality

I can’t express enough how much learning jQuery has expanded my ability to simply and dynamically add amazing effects very easily to my User Interfaces. Maybe I should start a jQuery blog? 🙂

One feature I come across a lot is the ability to expand and contract a section of the page, say a <div>. Before when I wanted to do this, I had to resort to either adding markup to my code and importing huge function-specific script files (ie, all they did was perform the expand/contract) or rely on ASP.NET’s AjaxToolkit’s Collapsible Panel Extender. While these solutions… worked… I was never really comfortable using them, and they were hardly reusable or scalable. Enter jQuery.

Let’s say I have a bit of HTML that is like so:

<p class="toggle">Expand/Collapse</p>
<div>
    <p>Some text goes here!</p>
</div>
<p class="toggle">Expand/Collapse</p>
<div>
    <p>Some more text goes here!</p>
</div>

If you wanted the ability to show/hide that following div, the jQuery is ridiculously simple:

$(document).ready(function() {
    $(".toggle").click(function () {
        $(this).next("div").slideToggle("fast");
    });
});

Yes, literally that’s it. So long as you keep with the HTML convention above, that’s all the jQuery you would need. You don’t have to add any extra markup or link one ID to another or anything. It’s all done via jQuery, and pretty much in one line ($(this).next("div").slideToggle("fast");).

Of course, sometimes you may want to do more. For instance, what if you wanted to change the text of the toggle button? Assume now that “Expand/Collapse” now reads “View Additional Info”. Here’s your jQuery:

$(document).ready(function() {
    $(".toggle").toggle(function () {
        $(this).text("Hide Additional Info")
        $(this).next("div").slideDown("fast");
        }, function() {
        $(this).text("View Additional Info")
        $(this).next("div").slideUp("fast");        
    });
});

Extremely simple, elegant, and even intuitive! If you ever doubted jQuery’s power before, you may want to reconsider. I sure did.

Advertisements

July 31, 2009 Posted by | jquery, Tips & Tricks | , | 3 Comments

Javascript: Setting the Month on a Date Object

While working with dates in Javascript I came across some weirdness that was messing with my date parsing. Apparently in Javascript, years and days are 1-based, but months are 0-based. To set the correct date:

var someDate = new Date(yourYear, yourMonth - 1, yourDay);

Crazy, I know, but hopefully this helps someone out.

July 28, 2009 Posted by | Javascript, Tips & Tricks | | Leave a comment