Hopefully this is an easy question. I have a div
that I want to toggle hidden/shown with a button
var toggle = document.getElementById("toggle");
var content = document.getElementById("content");
toggle.addEventListener("click", function() {
content.style.display = (content.dataset.toggled ^= 1) ? "block" : "none";
});
#content{
display:none;
}
Some content...
About the ^ bitwise XOR as I/O toggler
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
.classList.toggle()
var toggle = document.getElementById("toggle");
var content = document.getElementById("content");
toggle.addEventListener("click", function() {
content.classList.toggle("show");
});
#content{
display:none;
}
#content.show{
display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
Some content...
$("#toggle").on("click", function(){
$("#content").toggle(); // .fadeToggle() // .slideToggle()
});
#content{
display:none;
}
Some content...
.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). */
}
Some content...
and
(unsupported on IE and Opera Mini)
TOGGLE
Some content...
checkbox
[id^=toggle],
[id^=toggle] + *{
display:none;
}
[id^=toggle]:checked + *{
display:block;
}
Some content...
radio
[id^=switch],
[id^=switch] + *{
display:none;
}
[id^=switch]:checked + *{
display:block;
}
1 Merol Muspi...
2 Lorem Ipsum...
:target
(just to make sure you have it in your arsenal)
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:
var toggle = document.getElementById("toggle");
var content = document.getElementById("content");
toggle.addEventListener("click", function(){
content.classList.toggle("appear");
}, false);
#content{
/* DON'T USE DISPLAY NONE/BLOCK! Instead: */
background: #cf5;
padding: 10px;
position: absolute;
visibility: hidden;
opacity: 0;
transition: 0.6s;
-webkit-transition: 0.6s;
transform: translateX(-100%);
-webkit-transform: translateX(-100%);
}
#content.appear{
visibility: visible;
opacity: 1;
transform: translateX(0);
-webkit-transform: translateX(0);
}
Some Togglable content...