Sunday, October 7, 2012

A Simple Show/Hide Technique with jQuery

Today I learned a simple technique to show/hide parts of content on the page. In my sample application, I'm using it to display a part of a long blog post, and then at the end of the part to display a button that will show the rest of the post. The button initially says "Show more". When the button is clicked, it displays the previously hidden part and its text changes to "Show less". So, in essence, it toggles the display state of the div it is connected to, and its own text.

Additionally, I'm displaying posts dynamically, so for each post there is a div with the first part of the post, the div with the rest, and the toggle button. Here's how it works:

For each blog post in the model a div is created for the rest of the post, and a button. The ID for both is assigned dynamically using a simple counter.

@model Recipes.ViewModels.BlogViewModel
@{ int i = 0; }
@foreach (var post in Model.Posts)
    string divID = "hide" + i.ToString();
    string btnID = "btn" + i.ToString();
    <div id="middlecolumn">
        <div class="blogcontainer">
            <h3 class="title"><a href="#">@post.Title</a></h3>
            <div class="info"><span class="submitted">Submitted on @post.DateCreated</span></div>
            <div class="buttonlink"><a id=@btnID href="javascript:toggleDiv('@divID', '@btnID');">Show more</a></div>
            <div id=@divID  style="display:none">@MvcHtmlString.Create(post.RestOfContent)</div>
    i = i + 1;

The javaScript function toggleDiv() takes two parameters: div ID and button ID. First the function toggles the div display property by using the jQuery function toggle(). Next, based on the div display state, the button text is set to one of the two possible values. And that's it.

<script type="text/javascript">
    function toggleDiv(divId, btnId) {
        $("#" + divId).toggle();
        if ($("#" + divId).css('display') == 'none')
        {$("#" + btnId).html('Show more'); }
        { $("#" + btnId).html('Show less'); }

Here's the example of the page with the blog post

Rest of the post hidden

Rest of the post expanded


How to hide, show, or toggle your div
How to hide, show, or toggle your div with jQuery by . Also posted on my website

No comments: