user6224087
user6224087

Reputation:

Change Navigation Text Color on Scrolling and on click

I have different sections of div on a single page with different ids. Example:

<section>
    <div id="first"></div>
</section>

<section>
    <div id="second"></div>
</section>

<section>
    <div id="third"></div>
</section>

And I have a horizontal navigation say for example:

<div class="nav">
    <ut>
        <li><a href="#first">First</a></li>
        <li><a href="#second">Second</a></li>
        <li><a href="#third">Third</a></li> 
    </ul>
</div>

What I want is:

  1. When I scroll down to different sections the navigation text's color should change. For example, if I scroll down to <div id="second"></div> then the color of <li><a href="#second">Second</a></li> should change.

  2. If I click on any of the navigation link I straightaway jump to that particular section. The color of the navigation text should change then also.

  3. When I click on any of the navigation and jump to a particular section it suddenly appears without any effects. I want to add a slideUp type jquery effect on click.

Please help me devs.

Upvotes: 2

Views: 800

Answers (1)

user6224087
user6224087

Reputation:

I found the solution to my answer. The below code does it all. It changes the #id from the URL and according to it changes the color of the navigation font.

Code:

$(document).bind('scroll',function(e){
    $('div').each(function(){
        if ($(this).offset().top < window.pageYOffset + 10 && $(this).offset().top + $(this).height() > window.pageYOffset + 10){
            window.location.hash = $(this).attr('id');

            if($(this).attr('id') == "first"){
                $("#navlist a").css('color', 'white');
                $("#nav1").css('color', 'red');
            }else if($(this).attr('id') == "second"){
                $("#navlist a").css('color', 'white');
                $("#nav2").css('color', 'red');
            }else if($(this).attr('id') == "third"){
                $("#navlist a").css('color', 'white');
                $("#nav3").css('color', 'red');
            }

        }
    });
});

Upvotes: 1

Related Questions