javascript - How to change active tab on navbar when scrolling until a component is visible? - Stack Overflow

I have a navBar with multiple tabs which I can click and it scrolls me to the ponent (scrollToComponent

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
Add a ment  | 

1 Answer 1

Reset to default 3

Replying 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745674715a4639616.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信