Animated hamburger toggle
by Jesse M
HTML
<div class="hamburger">
<div class="bars">
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
</div>
CSS
.hamburger {
width: 40px;
height: 40px;
position: fixed;
top: 50%;
left: 50%;
display: block;
transform: translate(-50%, -50%);
background: #000;
border-radius: 10px;
padding: 0 0.5rem;
box-sizing: border-box;
}
.bars {
position: relative;
}
.bar1, .bar2, .bar3 {
width: 100%;
display: block;
background: #FFF;
height: 3px;
margin-bottom: 4px;
position: absolute;
}
.bar1 {
top: 11px;
}
.bar2 {
top: 18px;
}
.bar3 {
top: 25px;
}
JavaScript
$.fn.animateRotate = function(angle, duration, easing, complete) {
var args = $.speed(duration, easing, complete);
var step = args.step;
return this.each(function(i, e) {
args.complete = $.proxy(args.complete, e);
args.step = function(now) {
$.style(e, 'transform', 'rotate(' + now + 'deg)');
if (step) return step.apply(e, arguments);
};
$({deg: 0}).animate({deg: angle}, args);
});
};
$('.hamburger').click(function(){
if($(this).hasClass('ham-open')){
$('.bar1').animateRotate(180);
$('.bar3').animateRotate(-180);
$('.bar1').animate({top: '11px'});
$('.bar3').animate({top: '25px'}, function(){
$('.bar2').animate({opacity: 1});
});
$(this).removeClass('ham-open');
}else{
$('.bar2').animate({opacity: 0}, function(){
$('.bar1, .bar3').animate({top: '18px'}, function(){
$('.bar1').animateRotate(45);
$('.bar3').animateRotate(-45);
});
});
$(this).addClass('ham-open')
}
});