I have a navBar with multiple tabs which I can click and it scrolls me to the ponent (scrollToComponent), it also sets that tab as the active one.
I also want to do the oposite, scroll and when a ponent is visible it should mark the corresponding tab as the active one.
I found this fiddle, that demonstrates exactly what I need, but it uses Jquery, and the items that it scrolls to are not ponents, and all of them have the same height.
$(document).ready(function () {
$(document).on("scroll", onScroll);
function onScroll(event){
var scrollPos = $(document).scrollTop();
$('#menu-center a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('#menu-center ul li a').removeClass("active");
currLink.addClass("active");
}
else{
currLink.removeClass("active");
}
});
I have a navBar with multiple tabs which I can click and it scrolls me to the ponent (scrollToComponent), it also sets that tab as the active one.
I also want to do the oposite, scroll and when a ponent is visible it should mark the corresponding tab as the active one.
I found this fiddle, that demonstrates exactly what I need, but it uses Jquery, and the items that it scrolls to are not ponents, and all of them have the same height.
$(document).ready(function () {
$(document).on("scroll", onScroll);
function onScroll(event){
var scrollPos = $(document).scrollTop();
$('#menu-center a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('#menu-center ul li a').removeClass("active");
currLink.addClass("active");
}
else{
currLink.removeClass("active");
}
});
Share
Improve this question
edited Jun 19, 2020 at 19:31
Martin Pascale
asked Jun 16, 2020 at 18:34
Martin PascaleMartin Pascale
511 silver badge6 bronze badges
1 Answer
Reset to default 3Replying myself since it can be useful for someone on the future:
I made this codesandbox example using react-intersection-observer.
It has a custom hook that lets you know if the element is visible, then you would have to pare which element is on top, so you can decide which tab you want to set as the active one.