Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript slideUp / slideDown / one button

Tags:

javascript

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";
}
like image 478
NoName84 Avatar asked Dec 02 '22 13:12

NoName84


2 Answers

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>
like image 105
The Process Avatar answered Dec 04 '22 03:12

The Process


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>
like image 45
Patrick Evans Avatar answered Dec 04 '22 01:12

Patrick Evans