Achieving smooth transitions with CSS3 when removing a class

I've been attempting to implement animation transitions on a removed class, but unfortunately it's not working as expected. I referenced this link: CSS transition when class removed

I have tried setting the transition on the parent element and on two dynamically assigned classes, but none of these approaches seem to be successful.

The scenario I am dealing with involves changing classes based on

scroll greater than the offsetHeight of the section element
. When this condition is met, I want to add a class that animates the height from 0 to 100px. Conversely, if the scroll is lower, I aim to set the height from 100px back to 0.

Here is a snippet of my code:

let nav = document.querySelector(".nav-container");
document.addEventListener("scroll", () => {
      if (window.pageYOffset > 200) {
        nav.classList.remove("nav-container-helper");
      } else {
        nav.classList.add("nav-container-helper");
      }
      if (window.pageYOffset > this.navImg) {
        nav.classList.add("navigation-container-scroll");
      } else {
        if (nav.classList.contains("navigation-container-scroll")) {
          nav.classList.remove("navigation-container-scroll");
        }
      }
    });

CSS styles:

.nav-container {
  position: absolute;
  top: 0;
  z-index: 1070;
  width: 100vw;
  height: 0;
  overflow: hidden;
  transition: 0.25s height linear;
}
.nav-container-helper {
  height: 100px;
}

.navigation-container {
  height: 100vh;
}
.navigation-container-scroll {
  height: 100px;
  position: fixed;
  top: 0;
  background-color: $white;
  border-bottom: 4px solid $main-color;
  transition: 0.25s height linear;
}

HTML structure:

<div className="nav-container">
        <nav className="main-nav">
          <div className="nav-wrapper container">
            <ul className="container navigation">
              <li>
                <NavLink
                  className="link-left"
                  exact
                  activeClassName="active-main"
                  to="/"
                  onClick={this.goToTop}
                >
                  Homepage
                </NavLink>
              </li>
              <li>
                <NavLink
                  onClick={this.goToAbout}
                  to="/"
                  activeClassName={
                    window.pageYOffset > this.scroll ? "active-main" : ""
                  }
                  className="link-left"
                >
                  About Us
                </NavLink>
              </li>
              <li className="logo-container">
                <NavLink className="brand-logo" to="/">
                  <img src="./logo_studio.png" alt="" />
                </NavLink>
              </li>
              <li>
                <NavLink exact activeClassName="active-main" to="/gallery">
                  Gallery
                </NavLink>
              </li>
              <li>
                <NavLink exact activeClassName="active-main" to="/video">
                  Video
                </NavLink>
              </li>
            </ul>
          </div>
        </nav>
      </div>

Answer №1

Ensure to have an additional class for removing a class; in that case, you can add another class named leaving to facilitate the end animation.

Consider the following example:

    let nav = document.querySelector(".nav-container");
    document.addEventListener("scroll", () => {
          if (window.pageYOffset > 200) {
            nav.classList.add("nav-leaving");
            nav.classList.remove("nav-container-helper");
            setTimeout(() => {
               nav.classList.remove("nav-leaving");
            }, 200);
          } else {
            nav.classList.add("nav-container-helper");
          }
          if (window.pageYOffset > this.navImg) {
            nav.classList.add("navigation-container-scroll");
          } else {
            if (nav.classList.contains("navigation-container-scroll")) {
              nav.classList.remove("navigation-container-scroll");
            }
          }
        });

CSS

.nav-container.leaving {
  -webkit-animation: removeHeight 200ms forward; /* Safari 4.0 - 8.0 */
  animation: removeHeight 200ms forward;
}
@keyframes removeHeight {
     from {height: 100px;}
     to {height: 0;}
  }

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

Tips on how to incorporate a .js file into my .tsx file

I ran into an issue with webpack displaying the following message: ERROR in ./app/app.tsx (4,25): error TS2307: Cannot find module './sample-data'. The imports in my code are as follows: import * as React from 'react'; import * ...

When using v-for to render components and <selection>, is there a way to customize it for just one specific instance of the component?

How can I modify the selection in each instance separately when rendering elements of an array obtained from the backend using v-for? Currently, changing one selection affects all instances due to the v-model. Is there a way to target only one selection ...

Step-by-step guide to designing a custom eBay-inspired logo page using HTML and CSS

Recently, I stumbled upon a fascinating website design for eBay's new logo page. It got me thinking about how I could recreate something similar for my own website. The concept of having the logo visible through the gaps is quite intriguing. If you&a ...

Implementing a way to send nested objects back in response to a jQuery get request

Using jquery.get() to request data from the Spring-Boot backend: var url = "http://localhost:8080/api/v1/get_holdings?userId=1"; $.get(url, function(payload,status) { if (status == "success") { $.each ...

Analyzing the Threejs application for profiling purposes

Recently, I noticed that my webgl application developed using threejs is facing some performance issues in terms of FPS on certain machines. To diagnose the problem, I attempted profiling my application using Chrome's about:tracing feature, following ...

The setTimeout function within the map function does not output any JSX element

I have been pondering the possibility of creating animated buttons using setTimeout on map elements. As I delve into learning React Transition group, I came up with this code snippet: function NavItemSub(props) { const array1 = props.array1; return ( ...

Connecting to a fresh dynamic route does not impact the getInitialProps data

I am struggling to understand the difference between componentDidMount and getInitialProps. Despite my best efforts to research, I still can't figure out when to use each one in my specific case. Let me give you some context. I have a page called /co ...

Using jQuery to move a div to a specific location on the page

Is there a way to translate the position of div x and y using Jquery that is compatible with all browsers, such as IE 7, IE8, IE9, and IE10? I have attempted the following: <div id="s1" style="-ms-transform:translate(159,430)"> hello ...

I can only successfully make an Axios GET request when I input the complete server path

I am currently working on an eCommerce project that has a backend developed using Node.JS and express, while the front end is built using React. I successfully connected the React frontend to the backend by setting the server address as a proxy in the pack ...

Guide to storing data in the browser's local storage with a Node.js Express backend

Up until this point, I relied on cookies to store preferences for my websites. However, as time has passed, the data stored in these cookies has grown too large and now exceeds the limit of 4096 characters. Therefore, I need to explore an alternative meth ...

How come my TABLE element is not showing padding when using border-spacing?

Looking to add some padding above and below my TABLE element, I came across the border-spacing property. Here's my table: <table id="ranks"> <tbody><tr class="ranksHeaderRow"> <th></th> <th>Name ...

Accessing a Global Variable within a Node Express Class Module

Within my Node Express application, I defined a variable in app.js like so: let accounts = [checkingAccount, savingAccount] Now, I have a class file named account.js (not a route) and I need to access the accounts array from within it. How can I achieve t ...

Guide to traversing nested documents provided as a JSON payload and making updates to each document within a collection

I am currently faced with the task of updating multiple documents in a collection as part of an ecommerce project for my school. The challenge lies in how to update the quantity of items in these documents based on the quantity purchased by the client. Th ...

Attempting to bring in an image file into a React component

My attempt to add an image at the top of my file failed, so I am looking for help with importing it. The code I originally tried did not work. The image does not display using the code below <img src={require('../../blogPostImages/' + post.bl ...

Update the styling of buttons in CSS to feature a unique frame color other

Can anyone help me with styling Bootstrap buttons and removing the blue frame around them after they're clicked? Here's what I've tried: https://i.stack.imgur.com/jUD7J.png I've looked at various solutions online suggesting to use "ou ...

Troubleshooting: Issues with JQuery and setTimeout() functionality

While using JQuery to monitor key presses for an HTML game, I encountered an issue where adding the jquery code to my gameloop resulted in an error message stating that keydown was not defined. <html> <head> //...Included JS files ...

Unraveling complex JSON structures in Node.js

I've been working on parsing nested JSON data and here is the code I'm currently using var str = '{"key1": "value", "key2": "value1", "Key3": {"key31":"value 31"}}'; v ...

Switch Angular checkbox to display string values instead of boolean true/false

My task is to create three checkboxes in a form with values toggling between "optin" and "optout" as I check/uncheck the checkboxes. Additionally, all checkboxes should be checked by default for the "optin" value. I'm struggling to find a solution, an ...

The type provided to React.createElement is not valid - it should be a string for built-in components or a class/function for composite components

Encountered an error while using a for loop. Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s%s, undefined, You likely forgot to export your compone ...

Caution: It is important for each child to be assigned a distinct key - How to pass an array in

While following ReactJS tutorials on Scrimba, I came across a scenario where id props need to be passed in an array. import React from 'react'; import Joke from './components/Joke.js' import jokesData from './components/jokesDat ...