1

So I have a header and I want to change the colors of the links in the header when I start scrolling. The nav in the header is in a list:

<nav class="top-nav">
    <ul class="top-nav">
        <li><a href="#home" class="scroll">Home</a></li>
        <li><a href="#services" class="scroll">Services</a></li>
        <li><a href="#port" class="scroll">Portfolio</a></li>
        <li><a href="#team" class="scroll">Team</a></li>
        <li><a href="#contact" class="scroll">Contact</a></li>
    </ul>
</nav>

To change the header I use this code:

$(window).scroll(function(){
    if ($(window).scrollTop() >= 100) {
        $('.header').addClass('fixed');
        $(".top-nav").css("color", "grey");
        $(".logo").css("color", "grey");
    } 
    else {
        $('.header').removeClass('fixed');
        $("top-nav").css("color", "white");
        $(".logo").css("color", "white");
    }
});

The color of the logo text changes fine, and the fixed header applies fine, so the code works, I just don't know how to specify that the links in the top-nav should be changed.

2 Answers 2

3

You can just rewrite your JS as

$(window).scroll(function(){
    if ($(window).scrollTop() >= 100) {
        $('.header').addClass('fixed');
        $(".top-nav>ul>li>a").css("color", "grey");
        $(".logo").css("color", "grey");
    } 
    else {
        $('.header').removeClass('fixed');
        $(".top-nav>ul>li>a").css("color", "white");
        $(".logo").css("color", "white");
    }
});

where .top-nav>ul>li>a will correctly select your links in the top-nav.

Read more about the selectors in jQuery in the docs or here

Sign up to request clarification or add additional context in comments.

Comments

0

I agree with Lal, another way is simply add another class to the things you want to change color.

HTML:

<li><a href="#home" class="scroll changeColor">Home</a></li>

jQuery:

$(".changeColor").css("color", "white");

It's the same thing, except you can more easily add the class to other stuff if needed, and it's easier to deal with if you're not as familiar with how selectors work. As Lal said though, read up on them, especially if you're using CSS or jQuery, which you are.

By doing this, you could simplify your code to:

$(window).scroll(function(){
    if ($(window).scrollTop() >= 100) {
        $('.header').addClass('fixed');
        $(".changeColor").css("color", "grey");
    } 
    else {
        $('.header').removeClass('fixed');
        $(".changeColor").css("color", "white");
    }
});

You would just add the changeColor class to your logo and links. For many, it's easier than dealing with the many layers of the elements.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.