In this article, we’ll look at a very simple example of implementing an animated hamburger button.
You’ve probably seen similar buttons on websites with mobile layouts. Such a button can also be found in Bootstrap versions 3 and 4.
To implement this button, we’ll need:
- HTML
- CSS3 (in our case, we’ll use SCSS)
- JavaScript (specifically jQuery)
Here’s what our button looks like in HTML:
<div class="hamburger"> <span class="hamburger-line"></span> <span class="hamburger-line"></span> <span class="hamburger-line"></span> </div>
Nothing complicated here:
A `DIV` with the class “hamburger” is the button itself, with predefined dimensions.
Each `SPAN` with the class “hamburger-line” represents one of the lines of the button.
Next comes the SCSS code:
.hamburger {
width: 30px;
margin: 0 auto;
&-line {
width: 100%;
height: 4px;
background-color: #158100;
display: block;
-webkit-transition: all 0.3s ease-in-out;
-o-transition: all 0.3s ease-in-out;
transition: all 0.3s ease-in-out;
&:nth-child(2){
margin: 6px auto;
}
}
&:hover{
cursor: pointer;
}
&.hamburger-active .hamburger-line:nth-child(2){
opacity: 0;
}
&.hamburger-active .hamburger-line:nth-child(1){
-webkit-transform: translateY(10px) rotate(40deg);
-ms-transform: translateY(10px) rotate(40deg);
-o-transform: translateY(10px) rotate(40deg);
transform: translateY(10px) rotate(40deg);
}
&.hamburger-active .hamburger-line:nth-child(3){
-webkit-transform: translateY(-10px) rotate(-40deg);
-ms-transform: translateY(-10px) rotate(-40deg);
-o-transform: translateY(-10px) rotate(-40deg);
transform: translateY(-10px) rotate(-40deg);
}
}For those familiar with CSS, the code above shouldn't cause any issues. But for beginners, here’s a short explanation:
- The
transitionproperty enables animation - The
transformproperty allows element transformation :nth-childis a pseudo-class selector
And finally, the JavaScript code using jQuery:
$(document).ready(function(){
$(".hamburger").click(function(){
$(this).toggleClass("hamburger-active");
});
});Here, when the hamburger is clicked, we add or remove the “hamburger-active” class. This class is styled in CSS to animate the first and third lines with a 45-degree rotation, while the second line (the SPAN with the “hamburger-line” class) becomes hidden.
You can see the full implementation on this page.
