jQuery Show/Hide Content
[tweetmeme]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…
- The content inside the DIV tag should be hidden when the page loads
- On clicking the Title or the Image, the content should slide down. On clicking again, it should toggle back to hidden state.
- 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…
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…
Let me know if there is a better way of doing this.
Hope you found it useful! Happy jQuerying!
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
Hi Darshan,
Make sure you have the plus and minus images in your images folder.
You can get them from here http://www.fineicons.com/en/free-icons/web-symbols/
Cheers,
Sumit
[…] Lets say I have a web page which will have the following HTML output… View Article […]
I appreciate your website a lot. Will read all. Keep up to briliant work on it. Thank you
Thanks Shondra 🙂
After reading Your ideas is very good om your Blog. I adore. thank you for presenting this lovely information
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! 🙂
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.
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. 🙂
Nice work there James 🙂
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. 🙂
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.
Hi Sumit,
A simpe and well written post. Thank you
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!
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
George,
Put this script in document.ready…
var firstContent=$(“a.toggle”).first().attr(“title”);
$(firstContent).show();
Cheers,
Sumit
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
“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
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.
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.
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.
Appreciation to my father who told me on the
topic of this web site, this webpage is actually remarkable.
After looking at a few of the blog articles on your site,
I really like your way of blogging. I added it to my bookmark webpage list and will
be checking back soon. Take a look at my web site as well and let me know what you think.
I have mastered some essential things through
your site post. One other subject I would like to convey is that there are lots of games in the marketplace designed particularly for preschool age little ones.
They include things like pattern recognition, colors,
dogs, and patterns. These typically focus on familiarization instead of memorization. This will keep little
kids occupied without feeling like they are studying.
Thanks
That iss also true when buying a vehicle and paying
cash.This iss one of the areas that most deserve the attention of the
law. Coverage is applicable to only certain autos that are specifically scheduled on the policy.