Skip to content

Instantly share code, notes, and snippets.

@SKumarSpace
Created October 10, 2023 14:34
Show Gist options
  • Save SKumarSpace/8641dab6ccf1acffbafa76e17c430649 to your computer and use it in GitHub Desktop.
Save SKumarSpace/8641dab6ccf1acffbafa76e17c430649 to your computer and use it in GitHub Desktop.
Intersection Observer - Sticky Class Conditionally Applied
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
margin: 0px;
font-family: Roboto, Tahoma;
}
#logo-container {
background-color: #bdc3c7;
height: 100px;
text-align: center;
padding-top: 20px;
font-weight: bold;
}
#nav-container-top {
background-color: #bdc3c7;
min-height: 1px;
min-width: 1px;
}
#nav-container {
background-color: #2980b9;
height: 60px;
line-height: 60px;
color: white;
text-align: center;
font-size: 18px;
position: sticky;
top: 120px;
font-weight: 700;
transition: font-size 0.2s ease-in;
}
#nav-container:after {
content: " down 👇";
}
.nav-container-sticky {
background-color: #e74c3c !important;
font-size: 18px !important;
}
#nav-container.nav-container-sticky:after {
content: "up ☝";
}
#main-container {
background-color: #ecf0f1;
height: 2000px;
}
</style>
</head>
<body>
<div
id="logo-container"
style="background-color: aqua; top: 0px; position: sticky; z-index: 10"
>
Background
</div>
<div id="logo-container">Background2</div>
<div id="nav-container-top"></div>
<div id="nav-container" style="z-index: 30">
This will get sticky scroll
</div>
<div id="main-container"></div>
</body>
<script>
//var element = document.querySelector("#nav-container");
//Stickyfill.add(element);
//to check when element get's position sticky
var observer = new IntersectionObserver(
function (entries) {
// no intersection
if (entries[0].intersectionRatio === 0)
document
.querySelector("#nav-container")
.classList.add("nav-container-sticky");
// fully intersects
else if (entries[0].intersectionRatio === 1)
document
.querySelector("#nav-container")
.classList.remove("nav-container-sticky");
},
{
threshold: [0, 1],
}
);
observer.observe(document.querySelector("#nav-container-top"));
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment