0

I have tab panel like this:

enter image description here

And I want to do something like when a user scroll down the page, this panel will select the next tab instead of scrolling the whole page.

I found a similar implementation, but since all of my contents are inside this box, I have no clue how to do like that.

Code example for jsfiddle:

$(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");
        }
    });
}

This is their html:

<div class="m1 menu">
    <div id="menu-center">
        <ul>
            <li><a class="active" href="#home">Home</a>

            </li>
            <li><a href="#portfolio">Portfolio</a>

            </li>
            <li><a href="#about">About</a>

            </li>
            <li><a href="#contact">Contact</a>

            </li>
        </ul>
    </div>
</div>
<div id="home"></div>
<div id="portfolio"></div>
<div id="about"></div>
<div id="contact"></div>
William.D
  • 103
  • 7
  • `$('a').each(function () {$(this).removeClass('active');})` can be written as `$('a').removeClass('active');` and frankly that's not something you'd want. Are you sure you want to target every. single. anchor. in. your. document? No. – Roko C. Buljan Apr 06 '22 at 19:11
  • Oh that just the code from the example, in my case I would target my class – William.D Apr 06 '22 at 19:13
  • Why you use scroll smooth with jQuery when all you need is CSS: https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior ? because of the `+2` ?... `'swing'` ?.. – Roko C. Buljan Apr 06 '22 at 19:16
  • Regarding your question: you don't need jQuery at all, and what could help you is: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API – Roko C. Buljan Apr 06 '22 at 19:19
  • 1
    sorry, I should explain more clearly, but that piece of code I just found it online, but that's the good point about scrolling, I will look into the Intersection Observer part – William.D Apr 06 '22 at 19:20
  • Here's an example: https://stackoverflow.com/a/65519620/383904 – Roko C. Buljan Apr 06 '22 at 19:28
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/243667/discussion-between-william-d-and-roko-c-buljan). – William.D Apr 06 '22 at 20:58

0 Answers0