What is the best way for me to make my hamburger animation play in reverse?

Having trouble achieving smooth animation effects.

I've designed a burger icon using three divs:

<div class="container">
<div class="burger-contain">
    <div id="line-1" class="line"></div>
    <div id="line-2" class="line"></div>
    <div id="line-3" class="line"></div>
</div>
</div>

I have defined separate keyframes for each line:

.line:first-child {
   animation-name: firstChild;
   transform-origin: 30px 25px;
   animation-duration: 0.5s;
   animation-fill-mode: forwards;
   margin: 10px;
}

Here are the keyframes used:

@keyframes firstChild {
0% {transform: translateY(0);}
50% {transform: translateY(10px);}
100% {transform: rotate(-45deg);}
}

All three lines have slightly different animations. The second line disappears, while the third moves up instead of down.

To achieve the click function, I utilized jQuery to toggle between classes as follows:

$(document).ready(function(){

var line = $(".line");
var burger = $(".burger-contain")
var toggled = false;

burger.click(function(){
   triggerAnimation();
});

function triggerAnimation(){
   if (toggled === false){
   line.removeClass("reverse");
   line.addClass("animate");
   toggled = true;
} else {

   line.removeClass("animate");
   line.addClass("reverse");
   toggled = false; 
}

}


});

To reverse the animation, I intended to use animation-direction: reverse; in my CSS like this:

.line:first-child.reverse {
animation-name: firstChild;
transform-origin: 30px 25px;
animation-duration: 0.5s;
animation-fill-mode: forwards;
margin: 10px;
animation-direction: reverse;
}

This is applied to all three lines. However, an issue arises where the animation stops functioning after the initial run. There seems to be no transition between the states, causing the animation to only work once in both directions - from Burger to Cross and vice versa.

Is there a flaw in my logic or am I misunderstanding the concept behind reversing animations?

Answer №1

Your understanding of the reverse concept may not be entirely accurate.

When an animation is set to play in reverse, it essentially goes back to its end state and starts over again with each cycle. The animation steps are reversed, and even the timing functions change accordingly—like ease-in becoming ease-out.source

In your scenario, adding the 'reverse' attribute after the animation has already concluded will not restart the animation; instead, it will just swap the start and end states.

Let's consider a simple example. On hover, you'll notice a sudden jump in the animation instead of a fluid direction change because we have reversed the entire animation without adjusting the element's position. It's akin to observing a reflection in a mirror:

.box {
  width:50px;
  height:50px;
  background:red;
  animation:change 5s linear forwards;
}

@keyframes change {
  from {transform:translateX(0)}
  to {transform:translateX(300px)}
}

body:hover .box{
   animation-direction:reverse;
}
<div class="box">

</div>

After the animation completes, you can clearly see how the first and last states switch when hovering.


An alternate approach would be using transitions instead of animations, requiring less code for the effect.

Note: I've utilized 'hover,' but this can easily be replaced with a class toggle.

.menu {
  height:50px;
  width:60px;
  position:relative;
  margin:50px;
  background:
    linear-gradient(#000,#000) center/100% 10px no-repeat;
  transition:all 0s 0.5s;
}
.menu:before,
.menu:after{
  content:"";
  position:absolute;
  left:0;
  height:10px;
  width:100%;
  background:#000;
  transition:0.5s 0.5s top,0.5s 0.5s bottom,0.5s transform;
}
.menu:before {
  top:0;
}
.menu:after {
  bottom:0;
}

.menu:hover {
  background-size:0px 0px;
}

.menu:hover:before {
  top:calc(50% - 5px);
  transform:rotate(45deg);
  transition:0.5s top,0.5s 0.5s transform;
}

.menu:hover:after {
  bottom:calc(50% - 5px);
  transform:rotate(-45deg);
  transition:0.5s bottom,0.5s 0.5s transform;
}
<div class="menu">
  
</div>

Answer №2

Here is a working example: https://jsfiddle.net/upnhcw69/38/

The solution involves utilizing 2 animations and switching between them to ensure they are triggered correctly.

Upon the first click, the `firstChild` animation is activated, followed by the activation of the `firstChild2` animation upon the second click. These animations are defined using two classes with distinct properties.

.line{
   height: 10px;
   width: 100px;
   margin: 10px;
   background-color:red;
}

@keyframes firstChild {
  0% {transform: translateY(0);}
  50% {transform: translateY(10px);}
  100% {transform: rotate(-45deg);}
}

@keyframes firstChild2 {
  0% {transform: rotate(-45deg);}
  50% {transform: translateY(10px);}
  100% {transform: rotate(0deg);}
}

.animate {
   animation-name: firstChild;
   transform-origin: 30px 25px;
   animation-duration: 0.5s;
   animation-fill-mode: forwards;
}

.reverse {
    animation-name: firstChild2;
   transform-origin: 30px 25px;
   animation-duration: 0.5s;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Positioning CSS icons beside text

I'm having trouble aligning a close button I created in CSS with regular text. Although the containing span element seems to align with the adjacent text, it doesn't align properly with the child divs. <a class="event-filter button" href="#"& ...

How can I set a value using document.getElementById(idPopUPImage).innerHTML to create a static popup in Leaflet?

I added a leaflet map to my project which you can find on Codpen In the map, I've included a button key that displays an image in a popup when clicked. However, after closing the popup and reopening it, the image doesn't show unless I click the ...

Default modal overlay closure malfunctioning; encountering errors when manually managed through jQuery

A custom overlay has been designed and implemented. <div class="overlay modal" id="11"> <div class="background-overlay"></div> <div class="description"> <div class="hidden-xs"> <img src=' ...

What is the best way to eliminate the blank space between div elements on a webpage?

I'm currently working on enhancing my portfolio website, and I'm struggling to eliminate the excessive white space. After inspecting the element, it appears that there is styling related to ul.AMSI, but it's not referenced anywhere in my st ...

Specific solution in responsive design queries

Looking to modify the style of a div based on screen resolution. Here is an example: @media only (width: 320px){do something} I attempted using this code but it was not successful. Appreciate any assistance! ...

Python script unable to locate div popup using Selenium

Recently, I've been working on enhancing my selenium skills, but I'm facing a challenge in finding a solution to this particular issue. While experimenting with the functionality of the page located at: www.omegle.com When using selenium to cli ...

Encountering a 404 (Not Found) error in Laravel while attempting to load UI content using AJAX

Currently, I am attempting to implement a UI loading functionality within a dashboard using AJAX. The main objective is to refresh the UI without having to reload the entire page by clicking on a ul. This feature works perfectly with regular PHP, but when ...

jquery did not load properly in the Google Chrome extension

Why am I unable to use a jQuery script inside my "myscript.js" file in the following Google Chrome extension? Is jQuery not loaded within the "myscript.js" file? What changes need to be made in the manifest file to enable the usage of jQuery inside "myscri ...

Showcase -solely one property object- from numerous property objects enclosed within an array

Hello, I am seeking assistance as I have recently begun learning about angularJS. I am working with objects that have keys such as: scope.eventList=[]; for(){ var event = { id : hash, ...

Implement jQuery to close multiple div elements

My dilemma involves a series of divs with different manufacturer IDs listed as follows: manufacturer[1], manufacturer[2], manufacturer[3], ... etc ... In attempting to create a JavaScript for loop to hide each div, I discovered that it was not achievab ...

Identifying when an element hovers over a particular section

I am facing an issue with the side dot navigation on my website. The navigation is standard with a fixed position, but I also have two types of sections with different backgrounds - one white and the other black. The problem arises when the dots are not vi ...

Modify the text color of all input elements with Tailwind

I have been using this code in multiple sections of the app: <label className="input text-neutral-content"> Name <input type="text" className="grow text-base-content"/> </label> While I understand that ...

Validate input JQuery only when specific radio buttons are chosen

My form currently has basic validation set up like this: <script type="text/javascript"> $(function() { $("#postform").validate({ rules: { ...

What could be the reason for the sudden malfunction of the .tabs li:hover property on my

I'm having trouble with the :hover effect not working on my .tabs li element. I've tried commenting out my jQuery script, but it still won't apply. Can anyone help me figure out why? Here's a JSFiddle link for reference: https://jsfidd ...

JQuery validation inspecting which submission button is activated

How can I implement validation and determine which button the user has clicked? I have a submit button with the following HTML: <form id="form-post"> <button type="submit" id="one"> ONE </button> <button type="submit" id="two ...

Replace Ajax Success Function

Looking to customize the behavior of the jQuery ajax function by handling a default action upon successful execution, while still running the callback function specified in the options parameter. Essentially, I need to filter out specific tags from the res ...

What causes Font Awesome 5 icons to vanish when changing the font-family?

I am facing an issue with the code I have below. It changes the font style successfully, but it also causes the icon to disappear. Can anyone provide tips on how to ensure that the icon remains visible while changing the font style? <link rel="styles ...

Library written in JavaScript for extracting CSS that is relevant

Is there a JavaScript tool available that can extract the style information from HTML code? For instance, when given the following HTML snippet, it would output a style block containing all the computed styles applied to each of those elements? Input... ...

Web Essentials is experiencing a problem with minified CSS

Today, while using Web Essentials 2013 for Update 3 with Visual Studio Express 2013 for Web, I encountered an issue with the minified CSS file. The website I am currently working on is built on a Twitter Bootstrap platform and utilizes two separate CSS fil ...

Hold off on showing the image until it has finished loading

// Here's the code snippet angular .module('imgapp', []) .controller('mainCtrl', mainCtrl); function mainCtrl() { var vm = this; vm.first = { title: 'Image 1', url: 'http://www.image-mapper.com ...