I want to change the class of the header using intersection observer. The idea here is that I have a header with full height and width and when we scroll down to another div the header shrinks to a small bar.
This is my javascript code.
if('IntersectionObserver' in window){
const options = {
root: null,
rootMargin: '0px',
threshold: 0.0
}
callback = (entries) => {
const header = document.querySelector("header");
const IS_INTERSECTING = entries[0].isIntersecting;
if(!IS_INTERSECTING){
header.classList.replace("header_full","header");
return false;
}else if(IS_INTERSECTING){
header.classList.replace("header","header_full");
return false;
}else{
return false;
}
}
let observer = new IntersectionObserver(callback, options);
let target = document.querySelector('header');
observer.observe(target);
}
This is my markup
<div class="application">
<header class="header_full">
<div>
<img src="logo_2.png" alt="logo">
<h2>Intersection Observer</h2>
</div>
<div class="bars"></div>
</header>
<div class="full">full_1</div>
<div class="full">full_2</div>
<div class="full">full_3</div>
<div class="full">full_4</div>
<div class="full">full_5</div>
</div>
This is my scss file
%full{
height: 100vh;
}
body{
margin: unset;
background:whitesmoke;
font-family: Comfortaa;
}
.full{
@extend %full;
}
.header_full{
@extend %full;
background: goldenrod;
display: grid;
place-items:center;
position: relative;
& img{
height: 250px;
width:250px;
object-fit: contain;
}
& h2{
text-align: center;
color: rgb(60, 60, 60);
letter-spacing: 1.4px;
}
& .bars{
&::after{
content: "☰";
font-size:1.3rem;
}
height: 40px;
width: 40px;
display: grid;
place-items:center;
position:absolute;
top:10px;
right: 10px;
color: rgb(60,60,60);
}
}
header{
transition: all 500ms linear;
}
.header{
height: 100px;
max-height: 100px;;
background: goldenrod;
position: fixed;
top:0;
width: 100%;
padding: 10px;
box-sizing: border-box;
animation: bring_down 500ms linear;
& img{
height: 80px;
width:80px;
object-fit: contain;
}
& h2{
display: none;
}
& .bars{
position:static;
}
}
The problem I am facing is when I scroll down, the intersection observer keeps toggling the classes ie. header_full and header. making it flicker all the time. I have tried "observer.unobserve(header)" but the problem that I get is stops observing and thus makes the header change one time only.
I have also refered the following stack overflow questions but no luck.