How to slide a hidden div up/down on click of a button?

user2498890 picture user2498890 · Feb 27, 2014 · Viewed 42k times · Source

I want to achieve this type of a slide down except instead of on hover I think I need some sort of script that triggers the slide down on click and then click again to trigger the reverse slide up. I will have a div thats hidden (top: -400px; above the top of the page) and when the button is clicked with slide down and sit at top: 0;

HTML

<div class="container"><div class="one">Hover me to reveal new div</div>
<div class="two">I slid!<br>And I am higher than the div before me...</div>
</div>

CSS

.container {
overflow:hidden;
height: 60px;
}

.one {
position: relative;
top: 0;
background-color: lightblue;
z-index: 1;
}

.two {
position: relative;
top: -40px;
background-color: yellow;
z-index: -1;
-webkit-transition: top 1s;
-moz-transition: top 1s;
-o-transition: top 1s;
transition: top 1s;
}

.one:hover + .two {
top: 0px;
}

Here is a working fiddle http://jsfiddle.net/8ZFMJ/2/ - any help would be appreciated.

I have tried using slideToggle however this creates an 'expanding' effect which isn't the type of slide down I want to achieve.

Many thanks.

Answer

Mayank Tripathi picture Mayank Tripathi · Feb 27, 2014

Try this http://jsfiddle.net/webcarvers/8ZFMJ/34/

remove this:

.one:hover + .two {
    top: 0px;
}

add this with jQuery Js

$(document).ready(function(){
var clicked=true;
$(".one").on('click', function(){
    if(clicked)
    {
        clicked=false;
        $(".two").css({"top": 0});
    }
    else
    {
        clicked=true;
        $(".two").css({"top": "-40px"});
    }
});
});