I have a couple of anchor links that scroll to content cards:
<nav class="bg-light p-4 d-flex justify-content-between">
<div class="anchor-buttons">
<a href="#c1" class="btn btn-outline-primary">Content 1</a>
<a href="#c2" class="btn btn-outline-primary">Content 2</a>
</div>
</nav>
<section class="p-5">
<div class="card my-5 p-5" id="c1">Content 1</div>
<div class="card my-5 p-5" id="c2">Content 2</div>
</section>
The card that has been navigated to, is being highlighted by giving it an active class:
function highlightCard() {
$(".anchor-buttons a").on("click", function () {
var id = $(this).attr("href");
$(".active").removeClass("active"); // remove existing active
$(id).addClass("active"); // set current link as active
observeCard();
});
}
Next, I want to remove the class, when the element is scrolled out of the viewport.
I tried to use this code, but can't figure out how to connect it to the other function. When the target card is not in view, the intersection observer removes it right after it has been added via click.
function observeCard() {
const el = document.querySelector(".active");
const observer = new window.IntersectionObserver(
([entry]) => {
console.log(entry.boundingClientRect.top);
if (entry.isIntersecting) {
console.log("Enter");
return;
}
console.log("Leave");
$(".active").removeClass("active");
if (entry.boundingClientRect.top > 0) {
// do things if below
} else {
// do things if above
}
},
{
root: null,
threshold: 0
}
);
observer.observe(el);
}
Sandbox: https://codesandbox.io/s/long-platform-30qjk?file=/index.html:2095-2109
Thanks for any pointers!