Reputation: 1235
I've been playing around with this all evening, but can't seem to figure out whats wrong with my code.
When you click the menu
button, the navigation will show up, animated with CSS. When you click it again, it disappears. Also CSS animated.
But if you click it a third time, the class collapsed
gets added, and immediately removed again.
What is the correct way of doing this. Animating the height of an element with CSS, and toggling the display
after the animation with jQuery?
I've also tried multiple .on()
events, but unsuccesfull (see below)
$('body').on('click', '.icon-mobile-menu', function(e){
e.preventDefault();
$(this).addClass('menu-open');
$nav.addClass('collapsed').height(312);
}).on('click', '.menu-open', function(e){
e.preventDefault();
$(this).removeClass('menu-open');
$nav.css('height', '').on('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function(){
$nav.removeClass('collapsed');
});
});
Thanks.
Upvotes: 1
Views: 91
Reputation: 7579
u can try
(function ($) {
$(document).ready(function () {
$('.icon-mobile-menu').on('click', function () {
$(this).toggleClass('menu-open');
$('.navigation').toggleClass('nav-slide');
});
});
})(jQuery);
.icon-mobile-menu {
background: red;
padding: 5px 10px;
cursor: pointer;
}
.menu-open {
background: blue;
color: white;
}
.navigation {
margin-top: 4px;
background: green;
padding: 5px 10px;
opacity: 0;
height: 0;
overflow: hidden;
-moz-transition:all 0.35s cubic-bezier(0.7, 0, 0.3, 1);
-o-transition: all 0.35s cubic-bezier(0.7, 0, 0.3, 1);
-webkit-transition: all 0.35s cubic-bezier(0.7, 0, 0.3, 1);
transition: all 0.35s cubic-bezier(0.7, 0, 0.3, 1);
}
.nav-slide{
height: 75px;
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<header class="header">
<span class="icon-mobile-menu">menu</span>
</header>
<div class="navigation">
<ul>
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
</ul>
</div>
Upvotes: 0
Reputation: 1914
The problem is that the handler of the transition effect you are binding triggers EVERYTIME when there is a height change, which includes when you try to collapse the dialog.
Here is a working fix, although it is a bit dirty:
$(document).ready(function () {
var $nav = $('.navigation'),
$header = $('.header');
$('.icon-mobile-menu').on('click', function () {
$(this).toggleClass('menu-open');
if ($nav.hasClass('collapsed')) {
$nav.css('height', '').on('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function () {
// Fix goes here
if ($nav.height() == 0){
$(this).removeClass('collapsed');
}
});
} else {
$nav.addClass('collapsed').height(75); // fixed height is for demo purposes only.
}
});
});
http://jsfiddle.net/486egfut/12/
Note: Why your first click is working is because you only bind that transition handler on your first click.
Upvotes: 1