This is my first personal project and I am having trouble dynamically altering the sticky positioning on my header with JS. All I want to do is to remove the sticky positioning I have set on the head class after I have scrolled past the bottom of the intro class. How do I achieve this using JavaScript?
This is the html code I have for the header and intro sections.
<header id="head">
<div class="title">
<h1 style="font-size: 2.5rem; margin-left: 10px;">
Health & Wellness
</h1>
<img src="C:Tech StackWebsite DesignCSS PracticeeImagesdownload (2).png" style="height: 60px; width: 100px; border: none; object-fit: cover;">
</div>
<nav class="navigation">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav"></div>
<button type="button" class="btn btn-light" id="search"><i class="bi bi-search" style="font-size: 15px;"></i>Search</button>
<button class="btn btn-primary" id="home">Home</button>
<button class="btn btn-success" id="about">About</button>
<button class="btn btn-info" id="services" style="color: white">Services</button>
</div>
</nav>
</header>
<div class="intro" id="intro">
<h2>Health & Wellness Blog Articles</h2>
<p>Read posts from experts at Harvard Health Publishing covering a variety of health topics and perspectives on medical news.
</p>
</div>
Here is the CSS
#head{
display: flex;
justify-content: space-between;
align-items: center;
margin: 10px;
background-color: #CDFFFC;
min-height: 150px;
padding: 15px;
}
.sticky {
position: sticky;
top: 0;
width: 100%;
z-index: 1000;
background-color: #CDFFFC;
And here is the Javascript
window.addEventListener('scroll', function() {
const header = document.getElementById('head');
const introSection = document.getElementById ('intro');
// Calculate the bottom position of the intro section
const introBottom = introSection.offsetTop + introSection.offsetHeight;
if(window.scrollY >= introBottom) {
header.classList.remove('sticky');
}else {
header.classList.add('sticky');
}
});