4th day _ Styling header was done
learned how to make header position fixed when scroll down and position absolute when scroll up by css transition and adding two classes
// header shows up when users scroll down over 230px
window.onscroll = () => {
let currentScrollPosition = window.pageYOffset;
const header = document.querySelector("header");
if (
currentScrollPosition > 230 &&
!header.className.includes("scroll_down")
) {
header.classList.add("scroll_down");
setTimeout(() => {
header.classList.add("scroll_down_finish");
}, 0);
} else if (
// the position of header from fixed to absolute when users scroll up less than 230px
currentScrollPosition < 230 &&
header.className.includes("scroll_down")
) {
header.classList.remove("scroll_down");
header.classList.remove("scroll_down_finish");
}
};
This is an important usage with setTimeout(() => {
header.classList.add("scroll_down_finish");
}, 0);
in the above codes.
In order to distinguish the order of class "scroll_down" and class "scroll_down_finish", I found setTimeout with 0 that can add "scroll_down" first and add "scroll_down_finish" after.
To implement position of header is from "absolute" to "fixed" with a 0.3s transition.
The top value will change from top: -230px
to top: 0
.
Here's CSS codes:
header{
background: #ffffff;
position:absolute;
z-index: 10;
top:0;
left:0;
width: 100%;
height: 230px;
}
header.scroll_down{
position: fixed;
top: -230px;
}
header.scroll_down.scroll_down_finish{
transition: top .2s ease-in;
top: 0
}