2LeggedSpider

jQuery Show/Hide Content

Posted in jquery by Sumit Thomas on December 28, 2009

Here is a technique I normally use to show/hide a content in a div tag. This is quite an useful UI technique in situations where you have to show a Master-Child data, where the child data will be hidden initially and will be shown on demand on click of a image or button.

Lets say I have a web page which will have the following HTML output…

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>JQ Show Hide</title>
</head>
<body>
    <a href="javascript://" title="#content-1" class="toggle">
        <img src="images/plus.png" border="0" />
        Another URL Shortener and it is from Google </a>
    <div id="content-1" class="content">
        Goo.gl is Google’s version of URL Shortening service. Unlike its counterpart tinyurl.com
        or bit.ly, Goo.gl is not a stand alone tool to generate short URLs. For now, the
        only way you can shorten a URL using Goo.gl is by using the Google Toolbar or if
        you have a Feedburner account, integrate your Feedburner feeds with your Twitter
        account.
    </div>
</body>
</html>

Here I have a clickable Title Another URL Shortener and it is from Google and an Image followed by a content inside a div tag. To provide a better user experience we’ll set ourselves the following tasks…

  1. The content inside the DIV tag should be hidden when the page loads
  2. On clicking the Title or the Image, the content should slide down. On clicking again, it should toggle back to hidden state.
  3. The Image should change from plus to minus and vice-versa during the toggle.

Lets create a simple style sheet to perk up the look of the page.

        .toggle
        {
            font-size: large;
        }
        .toggle img
        {
            border-style: none;
        }
        .content
        {
            display: none;
            font-size: small;
        }

After adding a couple of content, our page will look like this…

Master Child Content

Finally, lets write the jQuery code to handle tasks 2 and 3

        $(document).ready(function() {
            $("a.toggle").click(function() {
                var img = $(this).find("img"); //get a handle of the image tag inside title link
                var src = $(img).attr("src"); //get the source of the image 

                //toggle the source of the image to show either plus/minus
                if (src.endsWith("plus.png"))
                    src = src.replace('plus.png', 'minus.png');
                else
                    src = src.replace('minus.png', 'plus.png');

                $(img).attr("src", src);
                
                //get the title of the anchor tag which corresponds to the id of the content div
                var content = $(this).attr("title"); 
                //toggle the display of the content div
                $(content).slideToggle();
            });
        });

        String.prototype.endsWith = function(str) {
            return this.lastIndexOf(str) == this.length - str.length;  
        }

endsWith is a custom javascript function which checks if a string ends with a given substring. This is useful in our case to check if the image source ends with plus.png or minus.png

Putting it all together, our final output will be as follows…

Master Child Content

Let me know if there is a better way of doing this.

Hope you found it useful! Happy jQuerying!

About these ads
Tagged with: , ,

22 Responses

Subscribe to comments with RSS.

  1. darshan said, on December 30, 2009 at 1:12 pm

    hi,

    first thank u for article…love the jQuery development.
    when i am toggling by clicking on link the image is not getting displayed? can you tell me the solution? thanks

  2. [...] Lets say I have a web page which will have the following HTML output… View Article [...]

  3. Shondra Ruscitti said, on January 18, 2010 at 9:04 am

    I appreciate your website a lot. Will read all. Keep up to briliant work on it. Thank you

  4. Madison Diiorio said, on January 29, 2010 at 11:12 pm

    After reading Your ideas is very good om your Blog. I adore. thank you for presenting this lovely information

  5. James Knight said, on March 15, 2011 at 2:55 am

    Hi! After fishing through numerous examples of how to do this, yours seems to suit what I need the most.
    What I would love to know is, is there a way to toggle the hidden div’s to be shown first when the page loads, then can be clicked to be hidden? Basically I’d like to be able to build a friends list with 3 different groups that are all shown, but you can hide each one if needed.

    Thanks in advance! :)

  6. James Knight said, on March 15, 2011 at 3:12 am

    Scratch that last post, figured it out pretty quickly. Just had to remove from the content div:

    display: none;

    I have another problem though… Is there a way to remove the title that appears or is there a way to toggle to buttons without using a title?
    Thanks again.

  7. James Knight said, on March 15, 2011 at 3:16 am

    Again, should have tried a bit harder to figure it out… XD

    I just replaced title=”XXXX” with id=”XXXX”

    For anyone else wanting to do this, just go into the .js and change:
    var content = $(this).attr(“title”);
    //toggle the display of the content div
    $(content).slideToggle();

    to:

    var content = $(this).attr(“id”);
    //toggle the display of the content div
    $(content).slideToggle();

    AGAIN!!! Thank you for this. You’ve no idea how much this has helped. :)

  8. James Knight said, on March 15, 2011 at 11:51 pm

    I also tried out swapping:
    var content = $(this).attr(“title”);

    to:
    var content = $(this).attr(“class”);

    That fitted what I was aiming for a lot better, to toggle a number of items to be hidden when selected.
    Thanks again. If you’d like to view what I’m working on, head to http://www.social-pie.com. We’re heading into closed beta in the next few weeks so look for us on Facebook and like the page to get in. :)

  9. Jolanda Vayda said, on April 16, 2011 at 6:53 pm

    I used to be very happy to seek out this internet-site.I wanted to thanks to your time for this wonderful read!! I positively having fun with each little little bit of it and I have you bookmarked to take a look at new stuff you weblog post.

  10. Pear said, on November 18, 2011 at 8:06 am

    Hi Sumit,

    A simpe and well written post. Thank you

  11. Dennis said, on November 30, 2011 at 2:57 am

    First, nice work! Easy and well written!
    From there, I saw someone kvetching about how to do this with images, vs. text.
    I did it like this:
    1) I updated showHide.js to be like this:

    ///////////////////////////////////////////////////
    // ShowHide plugin
    // Author: Ashley Ford – http://papermashup.com
    // Demo: Tutorial – http://papermashup.com/jquery-show-hide-plugin
    // Built: 19th August 2011
    ///////////////////////////////////////////////////

    (function ($) {
    $.fn.showHide = function (options) {

    //default vars for the plugin
    var defaults = {
    speed: 1000,
    easing: ”,
    changeText: 0,
    showText: ‘Show’,
    hideText: ‘Hide’,
    changeImg: 0, // <– New item
    showImg: '', // <– New item
    hideImg: '' // <– New item

    };
    var options = $.extend(defaults, options);

    $(this).click(function () {

    $('.toggleDiv').slideUp(options.speed, options.easing);
    // this var stores which button you've clicked
    var toggleClick = $(this);
    // this reads the rel attribute of the button to determine which div id to toggle
    var toggleDiv = $(this).attr('rel');

    // here we toggle show/hide the correct div at the right speed and using which easing effect
    $(toggleDiv).slideToggle(options.speed, options.easing, function() {
    // this only fires once the animation is completed
    if(options.changeText==1){
    $(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText);
    }

    if(options.changeImg==1){
    // this gets the handle for the image in the tag.
    var toggleImg = $("a.show_hide").find("img");

    //get the source of the image
    var toggleImgSrc = $(toggleImg).attr("src");

    if (toggleImgSrc == undefined)
    toggleImgSrc = options.hideImg;

    else if (toggleImgSrc.endsWith(options.showImg))
    toggleImgSrc = toggleImgSrc.replace(options.showImg, options.hideImg);

    else
    toggleImgSrc = toggleImgSrc.replace(options.hideImg, options.showImg);

    $(toggleImg).attr("src", toggleImgSrc);

    }

    });

    return false;

    });

    };
    })(jQuery);

    String.prototype.endsWith = function(str) {
    return this.lastIndexOf(str) == this.length – str.length;
    }

    2) In the head of my html doc, I used:

    $(document).ready(function(){
    $(‘.show_hide’).showHide({
    speed: 1500, // speed you want the toggle to happen
    changeImg: 1, // if you dont want the button image to change, set this to 0
    showImg: ‘images/plus.gif’, // the button image to show when a div is closed
    hideImg: ‘images/delete.gif’ // the button image to show when a div is open
    });
    });

    Finally, in the section of the html I am working with, I added:

    Exclude List:

    My interesting content goes here!

    Shazam! I’m done!
    Thanks again!

  12. George said, on March 6, 2012 at 6:37 pm

    What piece of script would have to be added, for the first DIV to start off being open.
    This way users could see that the result would be an expanded section, below the question.

    Always load initially, exactly as you have it in the below image:

    Thank you

    • Sumit Thomas said, on March 7, 2012 at 12:11 am

      George,

      Put this script in document.ready…

      var firstContent=$(“a.toggle”).first().attr(“title”);
      $(firstContent).show();

      Cheers,
      Sumit

  13. http://yahoo.com said, on February 10, 2013 at 8:22 am

    I really Believe blog, “jQuery Show/Hide Content 2LeggedSpider” was great!
    I reallycan’t see eye to eye with u more! Finally looks like I actuallyfound a blog site worth looking through. Thank you, Leora

  14. Cheri said, on March 2, 2013 at 10:23 am

    “jQuery Show/Hide Content | 2LeggedSpider”
    fueldistributorlouisiana honestly enables me ponder a tiny bit more.
    I really admired each and every single section of this blog post.
    Thank you ,Sven

  15. Online Geld Verdienen Met Youtube said, on August 18, 2014 at 10:58 am

    One means of avoiding having reponses which might be always
    in the ‘average’ or ‘middle’ range without giving a decisive opinion is usually to offer an even variety
    of choices for respondents to choose from. This could be the major reason why every
    website owner must have a fantastic web hosting plan.
    A good target is six or eight percent of one’s projected gross sales.

  16. Free scripting Language said, on September 27, 2014 at 3:24 pm

    I always usedd tto read paragraph in newqs papers buut nnow as I
    amm a user of net so from now I am using net for articles or
    reviews, thanks to web.

  17. phentermine said, on October 13, 2014 at 3:04 pm

    Beautifully shot and acted, it still found its detractors.
    Yep, you heard that right, they love themselves some porn. I protected my sight
    when the glare turned too much in addition to squinted through the smoke a cigarette to
    find Julie, but it has been pointless.

  18. dome hotel said, on October 23, 2014 at 2:05 am

    Appreciation to my father who told me on the
    topic of this web site, this webpage is actually remarkable.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: