StealthRT
StealthRT

Reputation: 10542

Changing CSS background color for one link while on that page

Hey all i am trying to only change a background color of a link in my NAV to a different color than all the rest of the nav links only when the user is on that particual page that the link is for.

The code is:

$("#nav li ul li a #changeBG1").css("background-color","red");

And the nav HTML looks a little like this:

<ul id="nav">
    <li><a href="index.php">home</a></li>
    <li><a href="custHelp.php">who we are</a>
    <ul>
        <li id="changeBG1"><a href="about.php">about</a></li>
        <li id="changeBG2"><a href="help.php">team</a></li>
    </ul>
</li>

However, it does not seem to change just that one, it changes ALL of them. I can not seem to find out how to call the ID of NAV and then the ID of changeBG1 so only that one will change.

The Jquery code is:

var url = window.location.href;

url = url.substr(url.lastIndexOf("/") + 1);
$("#theNav").find("a[href='" + url + "']").addClass("theNavsBG");

if (url == 'about.php'){
    $("#nav li ul li a #changeBG1").css("background-color","red");
}

Any help would be great! Thanks!

Upvotes: 0

Views: 2121

Answers (3)

saluce
saluce

Reputation: 13350

http://jsfiddle.net/saluce/LhbKv/1/

Make life simpler on yourself...

.active{
    background-color: red;
}​

...

$("#nav a[href$='" + url + "']").addClass("active");

This code will find the link that ends with the string in the url (courtesy of the $ in the selector) and add a class to that a tag. If you want to color the li, then use the .parent().

$("#nav a[href$='" + url + "']").parent().addClass("active");

Upvotes: 1

Josh Frankel
Josh Frankel

Reputation: 198

I would make a css class and then just add the class to that specific link using jquery to show that it is the current page.

CSS

.active {
   background-color: red;
}

jQuery

var url = window.location.href;
url = url.substr(url.lastIndexOf("/") + 1);

$("#nav li ul li a").removeClass('active');
$("a[href='" + url + "']").addClass('active');

Upvotes: 3

gdoron
gdoron

Reputation: 150253

Try this:

$("#changeBG1").css("background-color","red");

id is the best selector, you don't need to add it "stuff".

You can also add a class to that li:

$("#changeBG1").addClass('foo');

Anyway, it looks likt your selector should be:

$("#nav li ul li#changeBG1").css("background-color","red");

Upvotes: 2

Related Questions