I have a drop down menu that I want to slide down when the Menu button is clicked and slide up when it's clicked again. Also slide up when clicking anywhere else in the document.
This is what I got so far: jsfiddle
HTML:
<nav>
<a class="dropdown-toggle" href="#" title="Menu">Menu</a>
<ul class="dropdown">
<li><a href="#">Menu Item</a></li>
<li><a href="#">Menu</a></li>
<li><a href="#">Settings</a></li>
<li><a href="#">Search</a></li>
</ul>
</nav>
Jquery:
$(function() {
// Dropdown toggle
$('.dropdown-toggle').click(function() {
$(this).next('.dropdown').toggle(function() {
$('.dropdown').stop().animate({
top: '100%'
}, 'slow');
});
});
$(document).click(function(e) {
var target = e.target;
if (!$(target).is('.dropdown-toggle') && !$(target).parents().is('.dropdown-toggle')) {
$('.dropdown').toggle(function() {
$('.dropdown').stop().animate({
top: '-100px'
}, 'slow');
});
}
});
});
The problem with what I did is the animation happens only once and only when clicking to open the drop down menu.
Answering my own question for anyone who's interested, this is the code:
$(function() {
$('.dropdown').hide();
$('.dropdown-toggle').click(function(e) {
$('.dropdown').slideToggle(400);
$('.dropdown-toggle').slideDown('active');
$('.dropdown').toggleClass('is-active');
return false;
});
$(document).click(function() {
if ($('.dropdown').is(':visible')) {
$('.dropdown', this).slideUp();
$('.dropdown').removeClass('is-active');
}
});
});
body {
padding: 2em;
}
a {
text-decoration: none;
color: #000;
}
nav {
position: relative;
}
.dropdown-toggle {
padding: .5em 1em;
background: #777;
border-radius: .2em .2em 0 0;
}
.dropdown {
position: absolute;
margin-top: .5em;
background: #777;
min-width: 12em;
padding: 0;
top: 0;
left: 0;
-webkit-transform: translateY(-60px);
-ms-transform: translateY(-60px);
transform: translateY(-60px);
transition: transform .3s
}
.dropdown.is-active {
-webkit-transform: translateY(30px);
-ms-transform: translateY(30px);
transform: translateY(30px);
display: block
}
ul.dropdown li {
list-style-type: none;
}
ul.dropdown a {
text-decoration: none;
padding: .5em 1em;
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav><a class="dropdown-toggle" href="#" title="Menu">Menu</a>
<ul class="dropdown">
<li><a href="#">Menu Item</a>
</li>
<li><a href="#">Menu</a>
</li>
<li><a href="#">Settings</a>
</li>
<li><a href="#">Search</a>
</li>
</ul>
</nav>
I used toggleClass
and removeClass
to add the animation I wanted and that's translate (the idea originally from Slide and Push Menu tutorial):
-webkit-transform: translateY(-60px);
-ms-transform: translateY(-60px);
transform: translateY(-60px);
transition: transform .3s