I have been working on animating a mobile menu where the three stripes transform into an 'X' when clicked and revert back to three stripes when closed. The transition to an 'X' is working perfectly, but when closing the menu, it jumps back to three stripes abruptly instead of smoothly transitioning back. This is because I completely remove the x
class, but I am struggling to find a way to transition back to the original state smoothly.
Below is the code I have written so far:
HTML:
<button id="nav-toggle">
<span class="toggle-pin"></span>
<span class="toggle-pin"></span>
<span class="toggle-pin"></span>
</button>
CSS (sass):
#nav-toggle {
position: relative;
z-index: 9000;
float: right;
margin: 15px 15px 0 0;
background-color: transparent;
border: none;
outline: 0;
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-ms-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
transition: all 0.5s ease;
@include respondFrom(widescreen) {
display: none;
}
.toggle-pin {
width: 34px;
height: 4px;
background: palette();
display: block;
margin: 5px 0;
border-radius: 5px;
}
&.x {
.toggle-pin {
margin: 11px 0;
}
.toggle-pin:nth-child(1) {
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
transform: rotate(45deg);
-webkit-transition: -webkit-transform .4s;
transition: transform .4s;
}
.toggle-pin:nth-child(2) {
opacity: 0;
-webkit-transition: opacity .3s;
transition: opacity .3s;
}
.toggle-pin:nth-child(3) {
margin-top: -30px;
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
transform: rotate(-45deg);
-webkit-transition: -webkit-transform .4s;
transition: transform .4s;
}
}
}
The toggle script:
$navToggle.on('click', function() {
if ($navToggle.hasClass('x')) {
$navToggle.removeClass('x');
}
else {
$navToggle.addClass('x');
}
});