Unable to achieve CSS transition effect with height: 0, works fine with other values

I have been trying to implement a transition effect for when the header goes hidden, but it seems to disappear immediately. I've included the code below for reference:

function getScrollTop() {
    return window.pageYOffset || document.documentElement.scrollTop;
}

function showHeaderHidden() {
    document.getElementById('header').classList.add('hidden');
    document.getElementById('header').classList.remove('fixed');
}

function showHeaderFixed() {
    document.getElementById('header').classList.add('fixed');
    document.getElementById('header').classList.remove('hidden');
}

function showHeaderFull() {
    document.getElementById('header').classList.remove('fixed');
    document.getElementById('header').classList.remove('hidden'); 
}

var lastScrollTop = 0;

function atPageTop(scroll) {
    return scroll < 1;
}

function scrollingDown(scroll) {
    return scroll > lastScrollTop
}

function onWindowScroll() {
    var scrollTop = getScrollTop();
    
    if (scrollingDown(scrollTop)) {
        if (scrollTop > 300) {
            showHeaderHidden();
        } else {
            showHeaderFixed();
        }
    } else {
        if (atPageTop(scrollTop)) {
            showHeaderFull();
        } else {
            showHeaderFixed();
        }
    }
    
    lastScrollTop = scrollTop;
}

lastScrollTop = getScrollTop();

window.onscroll = function () {
  onWindowScroll();
};
body {
  height: 2000px;
  margin: 0px;
}

header {
  height: 120px;
  background: red;
  
  transition: .5s;
}

header.fixed {
  position: fixed;
z-index: 10;
top: 0;
left: 0;
width: 100%;
height: 45px;
  background: green;
  
  transition: .5s;
}

header.hidden {
  height: 0px;
}
<header id="header">
  
</header>

I've specified a transition for the hidden header as well, but it doesn't seem to be working as expected:

header.hidden {
  height: 0px;

  transition: .5s;
}

If anyone has any insights or solutions, I would greatly appreciate your help!

Thank you in advance:)

Answer №1

The main issue here lies in the removal of the fixed class during the second step, which causes the element to return to its original position. To rectify this problem, it is essential to retain this class alongside the hidden class:

function calculateScrollPosition() {
  return window.pageYOffset || document.documentElement.scrollTop;
}

function displayHeaderHidden() {
  document.getElementById('header').classList.add('hidden');
  /* Remove the following line: document.getElementById('header').classList.remove('fixed'); */
}

function displayHeaderFixed() {
  document.getElementById('header').classList.add('fixed');
  document.getElementById('header').classList.remove('hidden');
}

function displayHeaderFull() {
  document.getElementById('header').classList.remove('fixed');
  document.getElementById('header').classList.remove('hidden');
}

var previousScrollTop = 0;

function scrollTopAtPageTop(scroll) {
  return scroll < 1;
}

function scrollToBottom(scroll) {
  return scroll > lastScrollTop
}

function handleWindowScroll() {
  var currentScrollTop = calculateScrollPosition();

  if (scrollToBottom(currentScrollTop)) {
    if (currentScrollTop > 300) {
      displayHeaderHidden();
    } else {
      displayHeaderFixed();
    }
  } else {
    if (scrollTopAtPageTop(currentScrollTop)) {
      showHeaderFull();
    } else {
      showHeaderFixed();
    }
  }

  previousScrollTop = currentScrollTop;
}

previousScrollTop = getScrollTop();

window.onscroll = function() {
  handleWindowScroll();
};
body {
  height: 2000px;
  margin: 0px;
}

header {
  height: 120px;
  background: red;
  transition: .5s;
}

header.fixed {
  position: fixed;
  z-index: 10;
  top: 0;
  left: 0;
  width: 100%;
  height: 45px;
  background: green;
  /*transition: .5s; can be removed*/
}

header.hidden {
  height: 0px;
}
<header id="header">

</header>

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

How come Bootstrap displays dual tabs simultaneously?

Having trouble navigating tabs on my website built with bootstrap v4. Clicking between different tabs causes two to display at the same time, but the issue resolves itself after clicking through them a few times. What am I doing wrong? If you'd like ...

What is the process for inspecting the element within a div using jsname with JS?

Struggling to inspect elements within a DIV without using xpath. // Assert.assertEquals("Digite uma senha",driver.findElement(By.xpath("//*[@id=\"view_container\"]/div/div/div[2]/div/div[1]/div/form/span/section/div/div/div[1]/div[2]/div[2] ...

Issue with left alignment of Div element

After creating a responsive footer, I encountered an issue where the text HELP and back icon were not aligning to the left as intended and appeared stuck in the middle. How can I adjust them to move to the left side? Below is the code snippet for reference ...

Adjust the width of the column to only contain fixed content and not span the entire page

Check out my solution on Plunkr to see the issue I'm facing: Plunkr I'm dealing with a layout that includes a menu on the left and page contents on the right. My goal is to have the menu fixed in place so that it doesn't move when the page ...

What are the reasons why Bootstrap icons are not functioning properly in ReactJS?

I am facing an issue with bootstrap icons not working in ReactJS. Click here to view my buttons This is the code for my post items: import React from 'react'; const PostListItem = () => { return ( <li className="app-list ...

What is the process for validating the CSS background-image URL using Javascript?

The concept here is to verify the URL of the CSS element's id (.boot). If the URL matches, which it does, then it should display "hello world." However, despite everything seeming correct, the expected behavior is not occurring, and the reason behind ...

What is the most effective HTML table design? Is it better to have a single table with a large number of rows, or multiple tables with only a few rows

In order to create a web page that features numerous fields displayed in a row of tables, I am looking to categorize them separately and design each category's table uniquely. I'm curious if having multiple tables on a webpage impacts its speed. ...

Problem with the swipe direction in Flexslider when right-to-left language

I have integrated the flexslider with rtl support from a website called rtl-this.com. However, I am facing an issue where when swiping the slider on touch screens, it moves in the opposite direction. Can anyone suggest a solution to fix this problem? ...

Initial page load experiencing issues with paroller.js functionality

Upon hard refreshing the page in the middle section, there seems to be an issue with the paroller js transform: translateY(); CSS effect not functioning properly on the <div class="col col-6" data-paroller-factor="0.4" data-paroller-type="foreground" da ...

Mobile-exclusive carousel feature

I am currently working on a project where I need to create a carousel specifically designed for mobile devices. I want the carousel to display only one image at a time on screens with a resolution lower than 650px, while on larger screens, a standard grid ...

What is the best way to place a div in a static position for my specific situation

I need help positioning container 2 statically below container 1. The navigation bar is fixed, so it will be outside the flow of the page while container 1 is relative and will appear on top as if the navigation doesn't exist in the flow. However, whe ...

Is there a way to shift this header just a tad beneath the border?

Is there a way to reposition the title within the image’s border in an alternate location? I am currently utilizing a Moodle theme and have identified the specific CSS section responsible for creating the border. .course-content .section.main { bord ...

Using the float property in IE7 can cause a line break and may result in other divs being pushed down

Hey there, I've encountered a few issues with floats in IE multiple times. Here's an example to illustrate what I mean. Please note that this example functions properly in Firefox and Chrome. index.html <html> <link href="style.css" rel= ...

Achieve overlapping divs using the Grid Layout

My objective is to have the div overlap the next row(s) without pushing them down when it increases in size. I attempted to use position: absolute; but this caused issues with the Grid Layout structure. Preserving the shape of the grid is crucial to me ...

I'm having trouble getting the "spacing" styling attribute to work in Material UI when I attempt to space out elements within my Box component. Can anyone explain why this might be happening?

Within my React 16.10 application, I am utilizing materialUI components. Specifically, I have incorporated two buttons inside a Box element. <Box style={{ marginTop: "3rem", marginLeft: "1rem", display: "f ...

What is the best way to search for a CSS selector that includes an attribute beginning with the symbol '@'?

Whenever I want to target an element with a click event, I usually use the following jQuery selector: $('div[@click="login()"]') <div @click="login()"> Login </div> However, when I tried this approach, it resulted ...

WordPress sidebar on bottom due to conflict with 960 grid in IE 7/8

After successfully validating my site with w3c, I encountered one small issue. The "& errors" link needed to be replaced with just "&" for the Google Maps link. However, in IE 7/8, there seems to be a conflict with the layout of the site. The sidebar ...

Styling Navigation in Internet Explorer 7 and 8

I'm encountering issues with a drop-down menu system specifically in IE7 and 8. The functionality is smooth in Chrome and FF, but for some reason, it fails to apply certain styles and ends up misaligned in the IE7 and 8 browsers. You can check it ou ...

Customizing a toggle checkbox in Bootstrap 5: A guide to personalization

I am attempting to modify a toggle switch in Bootstrap 5.2. <!DOCTYPE html> <html lang="en> <head> <meta charset="UTF-8> <meta http-equiv="X-UA-Compatible" content="IE=edge> <meta name="viewport" content="wid ...