Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making navigation links highlight when relevant element passes underneath it, using JavaScript/JQuery?

I have a single page website with the navigation menu position:fixed at the top of the page.

When I click a link from the navigation menu the page scrolls to the appropriate section using this JQuery:

$('a[href^="#"]').live('click',function(event){
     event.preventDefault();
     var target_offset = $(this.hash).offset() ? $(this.hash).offset().top : 0;
     $('html, body').animate({scrollTop:target_offset}, 1200, 'easeOutExpo');
});

What I'd like to happen is when I manually scroll the page $(window).scroll(function(){...});, relevant to the section passing under the navigation menu #navi-container, the navigation link highlights using .addClass('activeNav');

like image 651
Nasir Avatar asked Dec 13 '11 21:12

Nasir


2 Answers

Check-out this jsfiddle I stumbled across a few days ago, I believe it's just what you're looking for: http://jsfiddle.net/x3V6Y/

$(function(){
    var sections = {},
        _height  = $(window).height(),
        i        = 0;

    // Grab positions of our sections
    $('.section').each(function(){
        sections[this.name] = $(this).offset().top;
    });

    $(document).scroll(function(){
        var $this   = $(this),
            pos     = $this.scrollTop(),
            $parent = {};

        for(i in sections){
            $parent = $('[name="' + i + '"]').parent();
            //you now have a reference to a jQuery object that is the parent of this section

            if(sections[i] > pos && sections[i] < pos + _height){
                $('a').removeClass('active');
                $('#nav_' + i).addClass('active');
            }  
        }
    });
});

I would like to note that if you end-up using this that you re-think the for(i in sections) loop as it is a big hit to performance. If you can, it is an excellent idea to use this kind of loop:

for (var i = 0, len = sections.length; i < len; i++) {
    //...
}

...but that requires a re-think of how to store the offsets of the section elements since this type of loop requires an array rather than an object (an object will work but it has to be zero-indexed and all the indexes have to be integers).

like image 132
Jasper Avatar answered Nov 10 '22 14:11

Jasper


This is what I came up with when trying to do this with vanilla js. It works for my purpose and it should be easy to tweak the if statement to fit your needs.

window.addEventListener('load', (e) => {

    let contentWrapper = document.querySelector("main");
    let mainNavLinks = document.querySelectorAll(".glossaryContainer a");

    if( mainNavLinks != null ){

        window.addEventListener("scroll", event => {

            let fromTop = window.scrollY ;
            let selectedEl = '';

            mainNavLinks.forEach(link => {

                let section = document.querySelector(link.hash);

                if ( ( section.offsetTop - section.offsetHeight + contentWrapper.offsetTop ) <= fromTop) {
                    selectedEl = link.parentElement;
                }
                
                link.parentElement.classList.remove("selected");

            });

            if( selectedEl ){
                selectedEl.classList.add("selected");
            }

        });
    }
});
    <nav class="glossaryContainer">
        <ul>
            <li><a href="#a">Section 1</a></li>
            <li><a href="#b">Section 2</a></li>
            <li><a href="#c">Section 3</a></li>
        </ul>
    </nav>

    <main>
        <section id="a">
            <h1>Section 1</h1>
            <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Officiis, blanditiis expedita? Earum eligendi pariatur quaerat quos expedita ab quibusdam ratione veniam in, mollitia fuga repudiandae?</p>
        </section>
        <section id="b">
            <h1>Section 2</h1>
            <p>Ratione nulla nam, ipsa dignissimos corrupti veniam nostrum, laudantium asperiores sequi numquam placeat velit voluptate in praesentium non labore unde incidunt laborum maxime quae magni.</p>
        </section>
        <section id="c">
            <h1>Section 3</h1>
            <p>Soluta quibusdam ad nostrum vel voluptate delectus sequi dolores quia quaerat officia corrupti, aperiam fugit facere debitis repudiandae praesentium sapiente inventore repellendus, nemo commodi alias!</p>
         </section>

    </main>
like image 27
Tom Hennessy Avatar answered Nov 10 '22 16:11

Tom Hennessy