Switching back and forth between classes prevents the animation from playing continuously, causing it to jump straight to the end

Currently, I am in the process of animating a hamburger menu with a unique twist. The idea is to have the top and bottom lines smoothly translate to the middle and then elegantly rotate into an X shape when clicked. My approach involves toggling between two classes, namely menu-open and menu-closed using jQuery. However, I encountered a peculiar issue. When I removed the CSS for the menu-closed animation, everything worked perfectly. Yet, upon adding back the CSS, the animations seemed to skip directly to the final frame without fully executing.

CSS

.navbar .mobile-menu.menu-open .line::before {
        animation: menu-open-top 250ms linear forwards;
    }

    .navbar .mobile-menu.menu-open .line {
        animation: menu-middle 250ms linear forwards;
    }

    .navbar .mobile-menu.menu-open .line::after {
        animation: menu-open-bottom 250ms linear forwards;
    }

    .navbar .mobile-menu.menu-closed .line::before {
        animation: menu-open-top 250ms linear reverse;
    }

    .navbar .mobile-menu.menu-closed .line {
        animation: menu-middle 250ms linear reverse;
    }

    .navbar .mobile-menu.menu-closed .line::after {
        animation: menu-open-bottom 250ms linear reverse;
    }

Animation

@keyframes menu-open-top {
    30% {
        bottom: 0;
    }
    60% {
        bottom: 0;
        transform: rotate(0) translate(0);
    }
    100% {
        transform: rotate(45deg) translate(5px, 5px);
        visibility: visible;
    }
}

@keyframes menu-middle {
    40% {
        visibility: hidden;
    }
    to {
        visibility: hidden;
    }
}

@keyframes menu-open-bottom {
    30% {
        top: 0;
    }
    60% {
        top: 0;
        transform: rotate(0) translate(0);
    }
    100% {
        transform: rotate(-45deg) translate(6px, -6px);
        visibility: visible;
    }
}

JS

$(".mobile-menu").click(expandMenu);

function expandMenu() {
    $(".primary-nav").toggleClass("menu-expand");
    $(this).toggleClass("menu-open menu-closed");
}

I can't seem to figure out what's missing. It feels like there may be a need to introduce new keyframes for the reverse animation, but that could possibly be unnecessary.

Edit: To provide more context, here is the accompanying HTML code:

HTML

<div class="mobile-menu menu-closed">
  <div class="line"></div>
</div>

Answer №1

If you're looking to achieve a simple animation with precise timing, consider making changes to prop values. While @keyframe animations are an option, they can be trickier to control and synchronize, especially in cases like this where it's essentially a two-step animation.

To toggle the menu when clicking on a mobile menu button, you can use the following JavaScript code snippet:

document.querySelector('.mobile-menu').addEventListener('click', ({
  target
}) => {
  target.closest('.mobile-menu').classList.toggle('menu-open');
})

For those who prefer SCSS, here's a link to view the same functionality implemented in SCSS: https://jsfiddle.net/websiter/dybre2f9/. I've utilized CSS variables for easy customization and reusability. Feel free to adjust the values according to your preferences.

It's worth noting that the choice of using bottom and top properties for animating instead of translateY was intentional. This approach allows for independent movement animations, enabling experimentation with various overlapping values and timing functions. The slight overlap between rotation and movement adds a touch of organic fluidity to the animation, giving the impression that the button is dynamically responding to the interaction. It's all about infusing some liveliness into the design!

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

Optimizing the performance of J2EE web applications

I am currently working on enhancing the performance of my web application. The application is java-based and is hosted on an Amazon cloud server with JBoss and Apache. One particular page in the application is experiencing a slow loading time of 13-14 sec ...

Center align the division within the list item

Check out the fiddle provided here: https://jsfiddle.net/5jnnutg8/ I am looking for a way to center align and display inline the "something #" list items. While the title "Hi" can be centered using text-align: center in css, this doesn't seem to wor ...

Is there a way to customize the Webpack output to incorporate specific options solely for a particular bundle?

Currently, I am using Webpack 4 to build multiple bundles. My requirement is to add the output options libraryTarget and library for a single bundle only. The default configuration looks like this: output: { path: path.resolve(__dirname, 'dist/j ...

Java - openpdf - Splitting words using hyphens

We are currently utilizing openpdf 1.3.26 template 2.1 to create PDFs from HTML and CSS. Within our coding, there is a div element styled as follows: .text-block{ display:block; text-align:justify; word-wrap: break-word; ...

The NextJS application briefly displays a restricted route component

I need to ensure that all routes containing 'dashboard' in the URL are protected globally. Currently, when I enter '/dashboard', the components display for about a second before redirecting to /login Is there a way to redirect users to ...

Enhancing Visuals with src="imageUrl within Html"

Is there a way to customize the appearance of images that are fetched from an API imageUrl? I would like to create some space between the columns but when the images are displayed on a medium to small screen, they appear too close together with no spacing. ...

Problem with X-editable clicking functionality on Chrome browser

Bootstrap version 3 Having trouble with X-editable inline mode - the button click is not hiding the inline form if there are no changes in the field. I found some older discussions about this issue in the thread linked below, but they are from 8 months ag ...

What is the best way to save javascript code without running it?

I've been attempting to insert AdSense JavaScript code into a specific div location using jQuery, but it appears that the JavaScript code does not function well inside a jQuery variable. It gets executed instead. Despite trying to encode it with PHP&a ...

What could be causing this issue where the call to my controller is not functioning properly?

Today, I am facing a challenge with implementing JavaScript code on my view in MVC4 project. Here is the snippet of code that's causing an issue: jQuery.ajax({ url: "/Object/GetMyObjects/", data: { __RequestVerificationToken: jQuery(" ...

What are the signs that an element was visible on screen prior to navigation?

Recently, I incorporated SlideUp and SlideDown jquery animations into my website. You can check it out by visiting (click the >>>). However, I noticed a small issue where when users navigate to a new page, they have to re-SlideUp the element that was sl ...

Enhancing the default functionality of React.FC within Next.js

Currently, I am working on a tutorial in Nextjs that employs the code snippet below in JavaScript. However, I am planning to transition it to TypeScript. Since I am relatively new to TypeScript, I have attempted various solutions from different sources but ...

The layout of my website is perfect when my laptop's zoom is set to 90%, but at 100% it starts overflowing

Currently, I am in the process of building a website on my laptop while following an instructor's video tutorial. It has been important for me to set the same pixel measurements as the instructor in order to replicate the design they provided. However ...

Getting PHP Post data into a jQuery ajax request can be achieved by using the `$_POST

I'm struggling to figure out how to pass the blog title into the data field of my ajax call. I've been searching for beginner tutorials on SQL, PHP, and AJAX, but haven't found anything that clarifies this issue. If anyone knows of any usefu ...

The module 'SharedModule' has imported an unexpected value of 'undefined'

When working with an Angular application, I want to be able to use the same component multiple times. The component that needs to be reused is called DynamicFormBuilderComponent, which is part of the DynamicFormModule. Since the application follows a lib ...

Using jQuery's AJAX method to parse XML and then splitting the resulting array

Can the last value of a string be retrieved and saved as a variable? An example of such a string is: tm="1610612741|Bulls|Chicago|CHI" Is it possible to extract just "CHI" from this string and store it in a variable? Maybe something like: var tm = $(th ...

The HTML email appears distorted on Yahoo and Outlook, but displays correctly on all other platforms

Basically, I have an HTML email that was converted from a PSD file. I sliced the layers, made some changes to the URLs, and did a test email. The email looks fine on most email clients, but when I send it to Yahoo Mail or Hotmail/Outlook and open it in Chr ...

Click the link to find the JSON node that corresponds to the onclick event

After parsing JSON, the JS code below is returning a list of movie titles for me. Each movie title node contains additional attributes and values that are not currently being displayed. My goal is to have the other values in that specific node displayed wh ...

Execute JavaScript script whenever the state changes

I have a large table with multiple HTML elements such as dropdowns, textboxes, radio buttons, and checkboxes. Additionally, I have a function that I want to execute whenever any of these items change. Whether it's a selection from a dropdown, typing i ...

Hiding Div with JavaScript (Quick and Easy)

Hey there, I'm looking to make regStart and regPage alternate visibility based on a click event. I'm still getting the hang of JavaScript so any simple answers would be appreciated. <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/x ...

What new skills should I acquire following my mastery of HTML and CSS?

I have a vision of creating a website similar to funcage.com, a site filled with funny pictures where users can register, upload their own content, vote, and leave comments. After dedicating myself to learning HTML & CSS for over a year and completing the ...