84

Hopefully this is an easy question. I have a div that I want to toggle hidden/shown with a button

<div id="newpost">
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
user547794
  • 14,263
  • 36
  • 103
  • 152

8 Answers8

142

Pure JavaScript:

var button = document.getElementById('button'); // Assumes element with id='button'

button.onclick = function() {
    var div = document.getElementById('newpost');
    if (div.style.display !== 'none') {
        div.style.display = 'none';
    }
    else {
        div.style.display = 'block';
    }
};

SEE DEMO

jQuery:

$("#button").click(function() { 
    // assumes element with id='button'
    $("#newpost").toggle();
});

SEE DEMO

Piyush Gupta
  • 2,181
  • 3
  • 13
  • 28
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • Hi, any idea how to make it toggle with a nice fadein/fadeout? – Aerodynamika Mar 05 '14 at 23:02
  • 1
    @deemeetree: You could pass `'slow'` to `toggle`. If you're using the pure JS solution let me know and I can come up with something for that – Andrew Whitaker Mar 06 '14 at 13:38
  • Thanks, @Andrew I also found that in the new jQuery there's fadeToggle – Aerodynamika Mar 06 '14 at 14:22
  • Mine doesn't come back in when I click the button again, I've done exactly what you've done on JFiddle... Do you know of any way to fix that? – Barry Michael Doyle Feb 23 '15 at 15:10
  • @BarryDoyle: I'd have to see the code... You might be better off starting a new question, just make sure you include the code you're having trouble with and if possible include an example of the problem you're seeing – Andrew Whitaker Feb 23 '15 at 15:20
  • 1
    I was checking out other questions and I came across an answer in this thread: http://stackoverflow.com/questions/18808112/jquery-toggle-function-not-working ... Apparently it's because the new versions of JQuery don't support toggle anymore. – Barry Michael Doyle Feb 23 '15 at 16:04
  • 1
    @BarryDoyle: Actually, [toggle-event](http://api.jquery.com/toggle-event/) was deprecated in 1.8. The way this answer uses [toggle](http://api.jquery.com/toggle) is still available, see this example: http://jsfiddle.net/KpFRb/532/ – Andrew Whitaker Feb 23 '15 at 16:14
  • any idea how to make a custom element with .show() and .hide() on it, e.g. MyElement extends HTMLElement ... ? – George Jan 21 '18 at 14:07
  • when the original element has display: none, it will have to click twice to display it – Nam Lee Mar 30 '21 at 06:25
68

Look at jQuery Toggle

HTML:

<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>

jQuery:

jQuery(document).ready(function(){
    jQuery('#hideshow').live('click', function(event) {        
         jQuery('#content').toggle('show');
    });
});

For versions of jQuery 1.7 and newer use

jQuery(document).ready(function(){
    jQuery('#hideshow').on('click', function(event) {        
        jQuery('#content').toggle('show');
    });
});

For reference, kindly check this demo

shifu
  • 672
  • 8
  • 37
Naveed
  • 41,517
  • 32
  • 98
  • 131
  • 1
    Now .live() is deprecated in 1.7,and removed in 1.9 so in new versions you can use .on() (for details https://api.jquery.com/on/ ) – Rohit Dubey Apr 24 '15 at 12:25
  • How do you set this to hide by default? Edit: Figured it out, just added the toggle before the code that catches the button push. – simonr2 Apr 19 '16 at 16:25
  • How about w/o jQuery? Everyone can do it with jQ – Green May 28 '16 at 11:23
  • 2
    I suppose `toggle('show')` is a typo (that some have blatantly copied and pasted into other answers) because only `'slow'` and `'fast'` are accepted strings for duration. It works nonetheless because I think any invalid string will default to `'slow'`. https://jsfiddle.net/d5y06e6o/ – Shikkediel Nov 15 '16 at 23:57
  • @simonr2 can you elaborate on what you did to make this hide by default? – petebocken Jul 27 '23 at 21:19
41

Since toggling using style like:

myElement.style.display = someBoolState ? "block" : "none"  

is a really bad idea, here are some examples in JS, jQuery, HTML, CSS:

JavaScript .classList.toggle()

const elToggle  = document.querySelector("#toggle");
const elContent = document.querySelector("#content");

elToggle.addEventListener("click", function() {
  elContent.classList.toggle("is-hidden");
});
.is-hidden {
  display: none;
}
<button id="toggle">TOGGLE</button>
<div id="content" class="is-hidden">Some content...</div>

The beauty of the above is that the styling is purely handled where it should, and that's in your stylesheet. Also, by removing the .is-hidden class your element will regain its original display mode, being it block, table, flex, or whatever.

jQuery .toggle()

.toggle()Docs
.fadeToggle()Docs
.slideToggle()Docs

$("#toggle").on("click", function(){
  $("#content").toggle();                 // .fadeToggle() // .slideToggle()
});
#content{
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>

jQuery - Toggle .toggleClass()Docs

.toggle() toggles an element's display "block"/"none" values

$("#toggle").on("click", function(){
  $("#content").toggleClass("show");
});
#content{
  display:none;
}
#content.show{
  display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>

HTML5 - Toggle using <summary> and <details>

(unsupported on IE and Opera Mini)

<details>
  <summary>TOGGLE</summary>
  <p>Some content...</p>
</details>

HTML - Toggle using checkbox

[id^=toggle],
[id^=toggle] + *{
  display:none;
}
[id^=toggle]:checked + *{
  display:block;
}
<label for="toggle-1">TOGGLE</label>

<input id="toggle-1" type="checkbox">
<div>Some content...</div>

HTML - Switch using radio

[id^=switch],
[id^=switch] + *{
  display:none;
}
[id^=switch]:checked + *{
  display:block;
}
<label for="switch-1">SHOW 1</label>
<label for="switch-2">SHOW 2</label>

<input id="switch-1" type="radio" name="tog">
<div>1 Merol Muspi...</div>

<input id="switch-2" type="radio" name="tog">
<div>2 Lorem Ipsum...</div>

CSS - Switch using :target

(just to make sure you have it in your arsenal)

[id^=switch] + *{
  display:none;
}
[id^=switch]:target + *{
  display:block;
}
<a href="#switch1">SHOW 1</a>
<a href="#switch2">SHOW 2</a>

<i id="switch1"></i>
<div>1 Merol Muspi ...</div>

<i id="switch2"></i>
<div>2 Lorem Ipsum...</div>

Animating class transition

If you pick one of JS / jQuery way to actually toggle a className, you can always add animated transitions to your element, here's a basic example:

const elToggle  = document.querySelector("#toggle");
const elContent = document.querySelector("#content");

elToggle.addEventListener("click", () => {
  elContent.classList.toggle("is-hidden");
});
#content {
  display: inline-flex; /* or whatever */
  transition: 0.6s;
}

.is-hidden {
  position: relative;
  visibility: hidden;
  opacity: 0;
  transform: scale(0);
}
<button id="toggle">TOGGLE</button>
<div id="content" class="is-hidden">Some Togglable content...</div>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • You cannot `display: none` element with transitions – Green May 28 '16 at 11:25
  • @Green no you cannot. That's the reason of the animated example. – Roko C. Buljan May 28 '16 at 13:02
  • Hi Sir @Roko C. Buljan is there a way to show the div initially in CSS - Switch using :target toggle please help I really need that.Thanks. – bilalmohib Feb 16 '21 at 18:16
  • 1
    @ProgrammingHobby absolutely, if you want to make "Default open" one of the above containers (that use `:target` toggle method) simply add the desired *hash* ID to the page URI i.e: `index.html#switch1` - and see the Element ID switch1 open right away. You can also manipulate the URL object using JS `URL.hash` - if needed: https://developer.mozilla.org/en-US/docs/Web/API/URL/hash – Roko C. Buljan Feb 17 '21 at 08:12
  • @Roko C. Buljan Thank you so much sir.Have a nice day.You answer was great and I have used that in many of mine projects.Thanks for that. – bilalmohib Feb 17 '21 at 13:57
13

Here's a plain Javascript way of doing toggle:

<script>
  var toggle = function() {
  var mydiv = document.getElementById('newpost');
  if (mydiv.style.display === 'block' || mydiv.style.display === '')
    mydiv.style.display = 'none';
  else
    mydiv.style.display = 'block'
  }
</script>

<div id="newpost">asdf</div>
<input type="button" value="btn" onclick="toggle();">
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
Jeff the Bear
  • 5,603
  • 3
  • 22
  • 18
  • 4
    Nice, plain JavaScript solution. I would just recommend that the input type be a button rather than submit since submit will post the form... – Paul Sasik Jan 17 '12 at 16:55
1

Try with opacity

div { transition: all 0.4s ease }
.hide { opacity: 0; }
<input onclick="newpost.classList.toggle('hide')" type="button" value="toggle">

<div id="newpost">Hello</div>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
0

This is how I hide and show content using a class. changing the class to nothing will change the display to block, changing the class to 'a' will show the display as none.

<!DOCTYPE html>
<html>
<head>
<style>
body  {
  background-color:#777777;
  }
block1{
  display:block; background-color:black; color:white; padding:20px; margin:20px;
  }
block1.a{
  display:none; background-color:black; color:white; padding:20px; margin:20px;
  }
</style>
</head>
<body>
<button onclick="document.getElementById('ID').setAttribute('class', '');">Open</button>
<button onclick="document.getElementById('ID').setAttribute('class', 'a');">Close</button>
<block1 id="ID" class="a">
<p>Testing</p>
</block1>
</body>
</html>
0
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#hideshow').click(function(){
    $('#content').toggle('show');
  });
});
</script>

And the html

<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>
Edwin Martin
  • 319
  • 3
  • 15
-1

You could use the following:

mydiv.style.display === 'block' = (mydiv.style.display === 'block' ? 'none' : 'block');

4444
  • 3,541
  • 10
  • 32
  • 43
morski
  • 1