Creating a fading header effect with a gradual transition as it disappears

I'm working on a header that should disappear when the user scrolls down and reappear when scrolling back up. I've managed to make the header reappear with a smooth transition, but the disappearing effect is instant, which is not what I want. I need the header to smoothly disappear with a 0.5s ease-in-out transition just like it reappears. Can anyone help me achieve this effect?

 ////Header scroll effect//////

    // Hide Header on on scroll down
    var didScroll;
    var lastScrollTop = 0;
    var delta = 10;
    var navbarHeight = $('header').outerHeight();

    $(window).scroll(function(){
        didScroll = true;
    });

    setInterval(function() {
        if (didScroll) {
            hasScrolled();
            didScroll = false;
        }
    }, 250);

    function hasScrolled() {
        var st = $(this).scrollTop();
        
        // Make sure user scroll more than delta
        if(Math.abs(lastScrollTop - st) <= delta)
            return;
        
        // If user scrolled down and are past the navbar, add class .nav_up.
        if (st > lastScrollTop && st > navbarHeight){
            // Scroll Down Disappear
            $('header').removeClass('header__top').addClass('nav_up');
            $('label').removeClass('menu__btn').addClass('nav_up');
        } else {
            // Scroll Up Reappear
            if(st + $(window).height() < $(document).height()) {
                $('header').removeClass('nav_up').addClass('header__top');
                $('label').removeClass('nav_up').addClass('menu__btn');
            }
        }
        
        lastScrollTop = st;
    }
body{
  height: 30000px;
  background-color: lightblue;
  color: white;
}
.header__top {
  width: 100%;
  height: 120px;
  background-color: #000;
  position: fixed;
  top: 0px;
  z-index: 5;
  border-bottom: 0.02rem solid #000 ;
  display: flex;
  box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
  transition: top 0.5s ease-in-out;
}
.nav_up { /*---scroll up effect---*/
  top: -120px;

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<header class="header__top">
   <p>header</p>
</header>
</body>

Answer №1

When you remove the class header__top from an element, it also removes the transition properties. To avoid this, you can add the target class and then remove the old class as a callback function:

////Header scroll effect//////

    // Hide Header on scroll down
    var didScroll;
    var lastScrollTop = 0;
    var delta = 10;
    var navbarHeight = $('header').outerHeight();

    $(window).scroll(function(){
        didScroll = true;
    });

    setInterval(function() {
        if (didScroll) {
            hasScrolled();
            didScroll = false;
        }
    }, 250);

    function hasScrolled() {
        var st = $(this).scrollTop();
        
        // Make sure user scrolls more than delta
        if(Math.abs(lastScrollTop - st) <= delta)
            return;
        
        // If user scrolls down and is past the navbar, add class .nav_up.
        if (st > lastScrollTop && st > navbarHeight){
            // Scroll Down Disappear
            $('header').addClass('nav_up',function(){$('header').removeClass('header__top')})
            $('label').removeClass('menu__btn').addClass('nav_up');
        } else {
            // Scroll Up Reappear
            if(st + $(window).height() < $(document).height()) {
                $('header').removeClass('nav_up').addClass('header__top');
                $('label').removeClass('nav_up').addClass('menu__btn');
            }
        }
        
        lastScrollTop = st;
    }
body{
  height: 30000px;
  background-color: lightblue;
  color: white;
}
.header__top {
  width: 100%;
  height: 120px;
  background-color: #000;
  position: fixed;
  top: 0px;
  z-index: 5;
  border-bottom: 0.02rem solid #000 ;
  display: flex;
  box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
  transition: top 0.5s ease-in-out;
}
.nav_up { /*---scroll up effect---*/
  top: -120px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<header class="header__top">
   <p>header</p>
</header>
</body>

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

PNG file unable to display in Google Chrome

I created an image using paint.net and saved it as a .png file. However, when I try to display the image on my website, only the borders show up without any image content. Here is the code I used: HTML <a href="home.php"><img id="logo" src="../i ...

Updating a d3.js force-directed graph may retain previous JSON data during the reloading process

Having a d3.js force-directed graph that pulls data from a JSON feed, I encounter an issue when clicking on a node. Although the updated JSON is correct, the displayed graph does not reflect this new data. It seems like the graph is retaining previous info ...

A commonly used method to adjust the width of a table column to accommodate the size of the child element

I have a specific table width of 776 pixels with three columns. The third column has a fixed width of 216 pixels, but the widths of the other two are unknown. I want the second column to adjust its width based on its content, and whatever space is left aft ...

Is there a way to improve or simplify this jQuery validation code?

I am implementing client side validation using jQuery to ensure all fields are filled in before proceeding. var passedValidation = new Boolean(true); // Validate Required Fields if ($('#fbsignup input.firstName').val().trim() == '') { ...

Issue with OBJLoader showing a blank screen

Does anyone have experience with rendering OBJ files using three.js? I'm having trouble getting them to display on the screen and would appreciate any help or advice. The strange thing is that a simple cube renders perfectly in my project. For those ...

Error: Trying to access the length property of an undefined or null reference in JSON formatted data fetched through Ajax

I am attempting to populate a jQuery DataTables with JSON data retrieved from a Web API ajax call, but encountering the following error: An unhandled exception occurred at line 38, column 314 in 0x800a138f - JavaScript runtime error: Unable to get proper ...

Having trouble getting Passport.js middleware to redirect properly with AJAX requests?

I am transferring some data from Javascript to Node through AJAX and JQuery. In Node, I have configured a post request and added a middleware to verify if the user is logged in (redirecting them to the login page if not). However, the res.redirect() in my ...

How can we manually trigger $(document).ready() from within the ready callback of head.js using jQuery?

I am in search of ways to enhance the loading speed of a web application, particularly one that encompasses numerous javascript files on every HTML page. My plan is to experiment with head.js on a specific page to observe if it has a positive impact on loa ...

Issue arises when attempting to transfer data collection object from Jquery ajax Method to MVC Controller resulting in null object being displayed

I am attempting to pass a data object to an MVC controller using a jQuery method. When I click the submit button, a data object is created in a JavaScript method. The data object is not null in the Ajax method. However, when I try to pass it to the MVC con ...

A specialized WordPress template that loads just the header and footer

I have encountered a strange issue while trying to create a custom template for WordPress. The index.php file is working perfectly fine - all elements load without any issues. Here is the code in index.php: <?php get_header(); ?> <?php if ( is_ ...

Using HTML to place an image tag close to an input element

I'm experiencing a strange issue where adding an img tag alongside an input and a span causes the input and span to shift downwards. <div> <span>Credit Points</span> <input type="text" name="credit_points" value="2.25"/> ...

Firefox consistently reports ajax status as error

One of my ajax requests is causing some confusion. $.ajax({ url: webURL, type: 'post', data: somedata, cache: false, datatype: "json", contentType: "application/json", success: successFunc, ...

The container or row I placed in the middle of the page content is not anchored to the bottom like it should be for footer widgets

I'm struggling with the code I've extracted. How can I move the footer widget to the bottom of the page? On some pages, the footer displays at the bottom because there isn't much content, but on one specific page, it appears in the middle of ...

Enable the ability to upload multiple images on a single page using droparea.js

I am currently utilizing droparea js for uploading images. However, I have encountered an issue where if I try to upload an image in one of the upload menus, it ends up changing all four upload menus simultaneously. <div class="col-md-12"> ...

Make sure the top edge of your Bootstrap 4 dropdown menu is perfectly aligned with the bottom edge of your

Trying to make a Bootstrap 4 navbar dropdown display right below the navigation bar, but it consistently shows slightly above the bottom edge of the navbar. Is there a way to make this happen without fixing the height of the navbar and using margin-top fo ...

In what ways can a distant ancestor influence its subsequent generations down the line?

As a beginner utilizing Bootstrap v5, I am in the process of creating a navbar using the following HTML code. Within this code, the parent element (ul) of my link items contains a class called "navbar-nav" which results in my link items being styled to s ...

Attempting to navigate the world of AJAX and PHP

My experience with AJAX is limited, but I am currently working on a project that requires a form to submit data without refreshing the page. The goal is to display the result in a modal window instead. To achieve this functionality, I understand that imple ...

Getting rid of unwanted scrollbars in a breeze

I am facing an issue with two nested divs that have the same height settings. The outer div has a max-width/height constraint along with overflow auto, causing scrollbars to appear when the inner content exceeds its dimensions. However, even if I resize ...

Implementing a jQuery for loop to iteratively print my function with increasing values

I'm currently facing a perplexing issue, but the solution should be straightforward. My mind is completely stuck and I can't figure out where I'm going wrong. Simply put, I want to repeat my function three times as illustrated below: If my ...

Preventing scrollbar-induced content shifting in Material-UI components: A guide

My browser app displays content dynamically, which can vary in length compared to the screen size. This causes a vertical scrollbar to appear and disappear on desktop browsers, leading to the content shifting left and right. To prevent this, I apply style ...