Line 1 simply loads the minimized jQuery v1.4.4 library. Once that is done, the rest is cake =) Line 3 defines the toggleDiv JavaScript function which takes one parameter: the id of the div to be toggled. Line 4 is where all the action takes place. The $("#"+divId) part is the powerful jQuery selector which selects the div that was passed to the function. I cannot say how easy jQuery makes it to select elements whether it is by id, class, or even by element types. Once our div is selected, we simply append jQuery’s toggle() function which automatically detects whether or not the content hidden and toggles it. On the HTML code level, the function toggles the display attribute between none and block.

The content in this div will hide and show (toggle) when the toggle is pressed.

</div>

The a tag is styled to look like a button and the onclick event uses our toggleDiv which passes the ‘myContent’ div ID as the argument. The rest of the HTML basically codes for our ‘myContent’ div whose content will be toggled by a click of the a tag.

That is it! There is no more need to reinvent the wheel my friends.

Here is a new demo in response to a request where only one div is displayed at any one time.

The HTML code contains 3 divs to start off with: 2 hidden and 1 displayed. Each link will launch the showonlyone JavaScript function and pass over the corresponding div ID.

function showonlyone(thechosenone){

$('.newboxes').each(function(index){

if($(this).attr("id")== thechosenone){

$(this).show(200);

}

else{

$(this).hide(600);

}

});

}

Line 2 contains some very cool uses of jQuery. Here we are looping through all divs with the class = "newboxes" which represents all 3 divs.

Line 3 checks to see if the div id in the current loop is equal to thechosenone which is the argument that was passed to the function.

If the id matches up, we use the .show() jQuery function to display the div. The argument 200 used in the .show() function will animate the display for a duration of 200 milliseconds. How cool is that =) If you leave it blank, the div will appear suddenly.

If the id does not match up, we simply use the .hide() jQuery function to hide the div. The argument 600 used in the .hide() function will animate the div so that it looks like it is sliding away. I used a higher number here so that you can see the difference in speed of the animations. Again, you can simply leave it blank if you want to make the div suddenly disappear.

That’s it!

If you would like all the divs to be hidden from the get go, simply use CSS to hide them all like so:

.newboxes{

display:none;

}

Update: This is a cleaner version of the showonlyone script that is more elegant and has done away with using table tags. The button also toggles the div instead of just being able to show the div.

This is a version of the updated script that slides the divs:

Here is another quick example using the jQuery .slideDown() and .slideUp() functions.

Everything is the same here except we are calling the .slideDown() and .slideUp() functions instead of the .show() and .hide() functions respectively. Even the animation duration is kept the same if you pass an argument to the function calls.

Here is the JavaScript code:

function slideonlyone(thechosenone){

$('.newboxes2').each(function(index){

if($(this).attr("id")== thechosenone){

$(this).slideDown(200);

}

else{

$(this).slideUp(600);

}

});

}

Not much explanation needed here. Same idea, different functions used.

Here we have an a tag that has the text that we want to toggle as well as the div content. Whenever the link text is clicked, it fires off the toggleAndChangeText() JavaScript function.

Here is the JavaScript code for the toggleAndChangeText() function:

function toggleAndChangeText(){

$('#divToToggle').toggle();

if($('#divToToggle').css('display')=='none'){

$('#aTag').html('Collapsed text mode &#9658');

}

else{

$('#aTag').html('Expanded text mode &#9660');

}

}

Whenever the toggleAndChangeText() is fired off, it will first toggle the div with our nice jQuery toggle() function in line 2. Then it will test if the div content is hidden (or if the display attribute is set to none) in line 3. If so, it will change the link to “Collapsed text mode &#9658”. Otherwise, the link text will be changed to “Expanded text mode &#9660” in line 7.

To reverse the effect and start with the content hidden, all we have to do is the following:

<aid="aTag"href="javascript:toggleAndChangeText();">

Collapsed text mode &#9658

</a>

<div id="divToToggle" style="display: none;">

Content that will be shown or hidden.<strong>

</div>

The inline CSS is the key to making this work. We start with the content hidden which our JavaScript will detect so it will toggle to make the content visible once the link is clicked.

Next up is a pretty cool demo where we use the .animate() jQuery function to help toggle just about any element. In this case, we’ll use an image of yours truly :)

I have to apologize for all the inline CSS. This is the easiest way for me to get these demos across without having to separate the styling (which is usually best practice). I am trying to do good here so I hope the HTML Gods will spare me this one time.

Anyway, the HTML is quite simple. It is just a div with some text inside and a silly image. Notice there is no JavaScript event attached to our div just yet. This is where our jQuery code comes in and saves the day!

$(document).ready(function(){

$('#clickme').click(function(){

$('#me').animate({

height:'toggle'

},2000

);

});

});

In line 1, we tell jQuery to wait until the DOM (Document Object Model) is fully loaded or when our page is fully rendered. We do this because we want to add functionality to our “click me” div. If the “click me” div has not yet loaded and this JavaScript executes, there is no element to work on. Game over.

Instead, we tell jQuery to wait until our “click me” div is in place, and then add a click event to it (line 2).

Lines 3-6 defines our click event by animating the $('#me') element which in this case is the image. If you are not used to jQuery syntax, $('#me') uses jQuery’s all-powerful selector to help us select the element with id = me.

Once we have our element selected, we apply the animate function to add animation to this element’s CSS properties. We first begin with line 4 which toggles the height of the element and preserves the height:width ratio which gives it a shrinking effect. We use toggle here so that you can keep pressing the button to toggle in and out. You can of course use show or hide just like in the previous demos.

Line 5 just indicates how long the duration of our animation will last in milliseconds. In this demo, it is 2000 milliseconds which translates to 2 seconds (I was in AP math in high school).

Here is a demo that toggles multiples elements by the class attribute.

Lines 12-13 codes for 2 buttons that toggles the odd number divs and even number divs respectively by calling the toggleByClass function and passing the respective class names.

Here is the JavaScript code:

function toggleByClass(className){

$("."+className).toggle();

}

Simple and sweet but a lot is going on here. Let’s dissect line 2 and cover each component separately.

$("."+className) uses the jQuery class selector with the className variable representing the class of the element(s) you want to select. In our demo, we use the oddNumber and evenNumber class names to select for their respective divs.

Once the divs are selected, we tack on the .toggle() jQuery function to hide and show the elements.

Note: If you have an issue with your code, please give me a URL to work with. It’s extremely difficult for me to help if I cannot actually see the code.

If you found that my code was helpful in any way, shape, or form and would like to buy me a beer, please use the Donate button below =) Cheers! OR…you can sign up for a free Dropbox account using my referral link =) If you are not aware of what Dropbox is, it is the most awesomest online backup application there and so much more…all for free.

Published by

Allen Liu

Building websites is a passion of mine. During the course of my work, I have created some snippets of code that I hope will prove useful to other developers.
View all posts by Allen Liu

392 thoughts on “How to hide, show, or toggle your div with jQuery”

Comment navigation

This is a great article and I like how elegant the functions are, instead of having to use IDs and create strings with JavaScript.

I wanted to know if it’s possible to use this code as a base for a sidebar (i.e. on click of a certain menu item, keep all the others hidden, and show its related div on the right hand side of the page).

I’ve tried to do this, but the menu items get pushed down because of the div being shown, instead of the menu items staying fixed and the shown div appearing on the right hand side. I think it has to do with the divs being nested, but since the `.find` function is used (therefore divs are tied to each other), I’m not sure of how to get around it.

That put me on the right track. Setting top to 0px and changing the position to fixed pushes all the divs to the top. The height of the bottom div could then be changed to 100% to match the page and that should cover site navigation.

Hello.
This article I found is amazing. But I come with a problem when applying on my website (not online yet, working locally).
The lower div are not being pushed down. See you example with the three containers, if I add a “hello” in a div after, it moves right and not down:

the bigger one being that the following div after the container does not slowly follow the toggles.

the smaller problem is that juts as in Item 1, I am trying to have the bottom box to take over 100% of the container’s width (here at 80%). Works for Item 1, but not 2 and 3 as they only take more horizontal space on the right.

Hi Allen,
I’m very new in coding, and now I’m working on a project where I’ve to show and hide two different elements by two different buttons.
It’s showing here:http://jsfiddle.net/Aladin/gtg7ofhx/
But what I want to do is when I click on >>Shaharukh button panel1 and Approve and Reject elements should be show and panel2 element should hide.
And when I click on >>Kajol button panel2 and Approve and Reject elements should also be show but panel1 element should hide.
Please help me in this code..
Thank you in advance

Love the code. Simple. I do have an issue with how the site im using uses this. Currently, the data I want users to be able to hide/show is shown by default. How could I make it visible by default?
Example the league page for our madden league. http://Www.daddyleagues.com/madscrubs
Notice the NFC Standings and AFC Standings are able to be hidden/shown but are shown by default. How can I change it that they are hidden when you visit the page first?

You are very generous for sharing all of this. I will definitely “buy you a beer” when I get paid for my current struggle.

Having said that, I have successfully applied your pure JavaScript showonlyone (version 2) and I have successfully applied your JQuery slideonlyone… I need the “close-self” feature of the first to fit the later.

I need the JQuery slideonlyone to display:none on a second click (without having to click on another activation point).

If you could point me in the right direction that would be great. I would post a fiddle or a url – but you’d just be looking at your own code and the website is in the sandbox.

Thank you much for your prompt reply. This is similar to the straight JS alternative to the JQuery I was working with. I was wondering if there was a way to add easing? That’s what attracted me to the JQuery solution.

I really don’t know much about coding but I am trying to get these elements into Mailchimp for an email campaign I have to send out daily (ideally I would like to be able to list the article title and then have the article text drop down once someone clicks on it, which most of these options seem like I could do that with).

However, putting these codes into Mailchimp do not result in a click-able email. Please advise and I apologize if it’s a really simple answer that I missed!

I’m not 100% sure but I don’t think that is possible. I know for sure that you won’t be able to embed Javascript in emails for security reasons. There may be a CSS hack that may allow you to do this but you may need to test it in an actual email. Here is a simple CSS example of showing and hiding content based on the hover pseudo-class:

I have a question about toggles multiples elements by the class attribute. How can I do that only one div(in this case only one class) is displayed at any one time (in your toggles multiples elements script)?

You wanted to give you a big Thank You! You tips on hiding and showing div(s) helped me ace my Udacity final test on Intro to Programing. I am still on my journey to learn and hopefully become a Jr. front end programer soon. I will keep this website on my favorite list and I am forever grateful for the resource you have given me.

Hey, Allen. I’m running into an issue whereby the script works only in certain browsers, IE and Chrome. I don’t have very much scripting knowledge, so my ability to troubleshoot is quite limited. Any idea why the script wouldn’t be working in Safari mobile or Firefox? (When I load your page here in both of those browsers all of examples work perfectly!!!)

Welp! When I tested the page yesterday, it wasn’t working across all browsers. Today, after having changed nothing with the script or code, the page seems to be functioning properly in both Safari Mobile and Firefox, as well as others. Can’t explain that one, but it’s doesn’t look like I need any assistance troubleshooting at this point. Ha!

Unfortunately, this doesn’t help much. I’d probably need the url of the page so that I can see the actual layout of the code. My guess is that you did not include a jQuery library. Include the following code within your head tags:

What this does is delay the execution of your JavaScript until the document is loaded. My guess is that your JavaScript is running but the html elements are not yet rendered so there is nothing to act upon.

Hi Allen, these tuts are amazing.
Can I request for one more piece of code?
I have a total of 27 elements. Initially I want to show 9 of them, afterwards there will be a button to show the next 9 elements, and the button will disappear once the elements finish showing. Can you help me with that?
Will definitely buy you a beer!