I am having trouble of solving a problem. I have 2 buttons, the one is for slideUp and the other is for slideDown. What i would like to do is to have one button that toggle instead of having 2.
Thanks.
I have this code in html:
<div id = "box">Show / Hide</div>
<button onclick="slideUp('box');">Slide Up</button>
<button onclick="slideDown('box');">Slide Down</button>
and i have this code in css:
body{
background:grey;
}
#box{
width:400px;
height:400px;
background:orange;
margin:0 auto;
margin-top:3%;
overflow:hidden;
}
and my javascript code is this:
function slideUp(el) {
var elem = document.getElementById(el);
elem.style.transition = "all 2s ease-in-out";
elem.style.height = "0px";
}
function slideDown(el) {
var elem = document.getElementById(el);
elem.style.transition = "all 2s ease-in-out";
elem.style.height = "400px";
}
You can create CSS class
with the height:0
rule, and toggle that class with JS:
var elem = document.getElementById("box");
function slide() {
elem.classList.toggle('hide');
}
.box {
width: 400px;
height: 400px;
overflow: hidden;
background: orange;
margin: 0 auto;
transition: all 0.4s ease-in-out;
}
.hide {
height: 0;
}
<button onclick="slide();">Slide Toggle</button>
<div id="box" class="box">Show / Hide</div>
Put the css properties into a class, add the class to your element, and then toggle the class that affect the height on/off of the element using classList.toggle()
function slideToggle(el) {
var elem = document.getElementById(el);
elem.classList.toggle("open");
}
body{
background:grey;
}
#box{
width:400px;
background:orange;
margin:0 auto;
margin-top:3%;
overflow:hidden;
}
.slider {
transition:all 2s ease-in-out;
height:0px;
}
.slider.open {
height:400px;
}
<div id = "box" class="slider">Show / Hide</div>
<button onclick="slideToggle('box');">Slide</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With