What is the best way to smoothly add or remove several classes to a div while scrolling?

Looking for assistance to create a fading effect where a logo fades out and a smaller version fades in as I scroll. The scaling aspect is currently functioning correctly on scroll (view JS Fiddle), but the fading transition needs some work, resulting in choppy animation (see JSFiddle here). Any advice on how to smooth out the fading transition would be greatly appreciated.

Javascript:

function scrollAnimation() {
  if ($(window).width() > 640){
    var scrollTop = $(window).scrollTop();

    if (scrollTop > 50) {
      $(".inner").addClass('scrolling');
      setTimeout(function() {
        $(".inner").removeClass('hide-logo').addClass('show-logo');
      }, 500);
    }
    else {
      $(".inner").addClass('hide-logo').removeClass('show-logo scrolling');
    };
  } else {
    $(".inner").removeClass('show-logo scrolling');
    $(".inner").addClass('hide-logo');
  }
}

$(window).on('scroll resize', function () {
  scrollAnimation();
});

Answer №1

The CSS property known as transition-delay allows you to control the timing of a transition's start, making it possible to delay the transition based on different triggers such as scrolling down.

If you need to wait for a transition to end before executing another action, you can utilize the transitionend event and attach a handler function to it.

// Keep track of logo state
var isLogoFullSize = true;

// Add listener to trigger fade-in effect after fade-out has finished
$(".site-header").on('transitionend', function() {
  $(this).removeClass('fade-out');
});

function handleScrollAnimation() {

    var scrollTopPosition = $(window).scrollTop();

    if (scrollTopPosition > 50 && isLogoFullSize) { // Change to smaller logo
      $(".logo").addClass('scrolling');
      $(".site-header").addClass('fade-out');
      isLogoFullSize = false;
    }

    if (scrollTopPosition < 50 && !isLogoFullSize) { // Switch back to full-size logo
      $(".logo").removeClass('scrolling');
      $(".site-header").addClass('fade-out');
      isLogoFullSize = true;
    }
}

$(window).on('scroll resize', handleScrollAnimation);
.site-header {
  position: sticky;
  top: 0;
  width: 100%;
  background-color: #000;
  opacity: 1;
  transition-property: opacity;
  transition-duration: .2s;
  transition-timing-function: easeInExpo;
}

img.logo {
  display: block;
  margin: 0 auto;
  height: 120px;
  padding: 5%;
  transition-property: height;
  transition-duration: .2s;
  transition-delay: .2s;
}

img.scrolling {
  height: 50px;
}

.site-header.fade-out {
  opacity: 0.6;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="site-header">
  <span class="inner">
  <img class="logo" src="http://upload.wikimedia.org/wikipedia/fr/c/c8/Twitter_Bird.svg" />
  </span>
</div>

<div class="text">
  <p>
    Insert your unique content here.
  </p>
  ...
  <p>
    More unique content goes in here.
  </p>
  <p>
    And more original text to showcase the rewritten passage.
  </p>
</div>

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 for utilizing the value obtained from an AJAX URL in Yii

Recently I started using Yii and I have a form with a combo box and a text field. What I want to achieve is changing the value of the text field based on the selection made in the combo box. I am able to get an AJAX url by changing the combo box value, and ...

The precision of CSS width percentages

Which is narrower, width: 33.3%, width: 33.3333333%, or width: calc(100% / 3);? In mathematics, the latter equals to 33.33... (infinite) but in CSS, which one actually results in a narrower width? ...

Execute an asynchronous request using Javascript to communicate with a Spring Controller

I've created a JSP page that includes some JavaScript code: function sendData(tableID) { var table = document.getElementById(tableID); var dataArray= new Array(); for (var i = 1;i<table.rows.length; i++){ var row = table. ...

Troubleshooting a dropdown selection problem in an HTML form

I've been working on simplifying a login form, which used to function properly when username and password were manually entered. Now, I'm looking to create a drop-down menu for the username field using data from a MySql database. Here is the cod ...

What is the best way to use jQuery to toggle the visibility of a background?

Check out my CSS below: #load-icon { background: url(/Images/loaders/mask-loader.gif); background-repeat: no-repeat; z-index: 99; width: 32px; height: 32px; z-index: 99; margin-top: 9px; margin-bottom: 9px; margin-right: 5px; ...

Some suggestions for updating two div elements using only one Ajax response

My website features a signin() button that I want to enhance with ajax functionality. When the button is clicked, I need it to update two divs: one displaying a personalized welcome message, and the other showcasing a statistics table in a different locati ...

Start the Nuxt.js project using docker-compose

I'm currently facing some challenges while trying to deploy my nuxt project using Docker. I have created a Dockerfile, docker-compose.yml, and also the .dockerignore file. However, I am encountering errors during the process. This is my first time wor ...

Troubleshooting a Multi-dimensional Array Reference Issue

Currently, I am working with an Array and need to modify the last item by pushing it back. Below is a simplified version of the code: var array = [ [ [0,1,2], [3,4,5] ] ]; //other stuff... var add = array[0].slice(); //creat ...

Steps to generating a dynamic fabric canvas upon opening a new window

There seems to be an issue with the code below. When I click the button next to the canvas, my intention is to have a new window open displaying the canvas in full view. However, it's not working as expected. Can someone please assist me in troublesho ...

Having Trouble with Auth0 React Quickstart Login: Error 401 Unauthorized

Having issues with the react quickstart for basic login and logout using auth0. The callback URLs, logout URLs, web origins, and CORS allowed origins are all set to http://localhost:3000. Application type is configured as SPA, however, upon logging in I ...

Ways to modify the gap between buttons using CSS

I am faced with a design challenge on my home page. I want to add some spacing between the buttons so they are not too close to each other, but for some reason margin-top and margin-bottom properties are not working as expected. Can you help me figure out ...

Having trouble with Angular JS's ngRoute feature not functioning properly

I've been struggling with my ngRoute implementation. I seem to be unable to load the 'ngRoute' module for some reason. Whenever I run this code, I just end up with a blank page. Below is my app.js file: var app = angular.module('tutor ...

stop all HTML5 videos when a specific video is played using jQuery

I am facing an issue with 10 HTML5 videos on the same page, CHALLENGE Whenever I click on different videos, they all start playing simultaneously... <div><video class="SetVideo"></video><button class="videoP"></button>< ...

How to specify a single kind of JavaScript object using Typescript

Let's say we have an object structured as follows: const obj = [ { createdAt: "2022-10-25T08:06:29.392Z", updatedAt: "2022-10-25T08:06:29.392Z"}, { createdAt: "2022-10-25T08:06:29.392Z", animal: "cat"} ] We ...

CloudFront for Amazon - Limit MP3 playback to designated website

I've been trying to find a solution for allowing mp3 files in an Amazon S3 bucket paired with Cloudfront to be streamed directly on my site without revealing the source URL of the mp3s. I want to prevent others from sharing or leeching the link by vie ...

Creating and customizing forms using React JS

Currently, I am working on developing an edit form using React JS. The form consists of multiple components with one child component responsible for passing all changes made to a hook in the main component for updating data in Firebase. Main Component con ...

Having trouble viewing the page of a new package you published on the NPM Website?

Today, I officially released an NPM package called jhp-serve. It can be easily installed using npm install or run with npx. You can even find it in the search results here: https://www.npmjs.com/search?q=jhp. However, when attempting to view its page by cl ...

Is the video failing due to excessive adjustments of the video's currentTime?

Utilizing both user drag event and keypresses to adjust the position in an HTML5 video element, I am updating the video time with the following line of code: video.currentTime = toTime; Additionally, I am updating a canvas based on the video's posit ...

Tips for customizing the CSS styling of the validation ng-class error

Seeking advice: Is there a way to customize the CSS style of the 'error' validation error for ng-class in Bootstrap v3? This is my current code: ng-class="(form.datos.$invalid) && ( form.datos.$touched || submitted) ? 'error&apos ...

Using Jquery to toggle the visibility of divs based on radio button selections

I am struggling to hide the divs with the radio buttons until their title is clicked on. However, I am facing issues as they are not showing up when their title is clicked on. Any assistance would be greatly appreciated. SPIKE <!DOCTYPE html> &l ...