paulina
paulina

Reputation: 209

Change link css color of specific class with JS

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.

Upvotes: 1

Views: 181

Answers (2)

Fata1Err0r
Fata1Err0r

Reputation: 816

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.

Upvotes: 0

Lal
Lal

Reputation: 14810

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

Upvotes: 3

Related Questions