msqar msqar - 4 days ago 4
CSS Question

How can I make this div slide down from top with jQuery?

So I have 2 divs children of a display block parent. I would like to make div #2 (green) be on top of div #1 (red). With "on top" I'm not talking about z-index, I'm talking about literally being on top of the other. And then I was wondering if there could be a way to make div #2 slideDown()

As far as I tested, jQuery slideDown() or slideUp() works differently.
In the demo I made, when I run

$('.item-1').slideUp();


The item 2 is sliding up instead of item 1, why is that? I'm getting confused.

Any hints would be appreciated,

Thanks in advance.



window.slide = function() {
$('.item-1').slideUp();
}

.items-container {
height: 400px;
width: 240px;
background-color: #c3c3c3;
display: block;
/* overflow: hidden; */
}

.item {
height: 100%;
width: 240px;
position: relative;
font-size: 30px;
text-align: center;
vertical-alignment: middle;
}

.item-1 {
background-color: red;
}

.item-2 {
float: left;
position: relative;
background-color: green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="slide()">
Click me!
</button>

<div class="items-container">
<div class="item item-1">
1
</div>
<div class="item item-2">
2
</div>
</div>




Answer

jQuery's slideUp() and slideDown() methods animate the height of the matched elements, not position as you seemed to want: http://api.jquery.com/slideUp/.

What you seem to want is to translate the div it so that it moves on top of the first one.

http://www.w3schools.com/css/css3_2dtransforms.asp

window.slideUp = function() {
	$('.item-2').addClass('slideUp');
}

window.slideDown = function() {
	$('.item-2').removeClass('slideUp');
}
.items-container {
  height: 100px;
  width: 240px;
  background-color: #c3c3c3;
  display: block;
  /* overflow: hidden; */
}

.item {
  height: 100%;
  width: 240px;
  position: relative;
  font-size: 30px;
  text-align: center;
  vertical-alignment: middle;
}

.item-1 {
  background-color: red;
}

.item-2 {
  position: relative;
  transition: transform linear 1s;
  background-color: green;
}

.slideUp
{
  transform: translate(0,-100%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="slideUp()">
SlideUp!
</button>
<button onclick="slideDown()">
SlideDown!
</button>

<div class="items-container">
  <div class="item item-1">
    1
  </div>
  <div class="item item-2">
    2
  </div>
</div>

Comments