Discus
Discus

Reputation: 21

navbar change color on click html

I'm running into issues on my first ever website. I have successfully created a navigation bar at the top which looks and acts somewhat how I want it to (other than the color scheme but that can come later). The issue is that whenever I click a different link on the bar I want that box to change color, but it is currently stuck highlighted on the homepage. I think this is something super simple but i cannot find it. Thank you for the help.

body
{
    font-family:sans-serif;
    width: 100%;
    margin: 0px;
}

/* upper strip holding the tabs*/
ul
{
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    position:fixed;
    top: 0px;
    width: 100%;
    background-color: #328CC1
}

li
{
    float:left;
    border-right:3px solid #30FFE3;
}


li a
{
    display: block;
    color: whitesmoke;
    text-decoration: none;
    padding: 14px 16px;
    text-align: center;

}

li a:hover:not(.active) 
{
    background-color: #111;
}

a.active
{
    background-color: #EAB126

}
<ul>
    <li><a class="active" href="#home">Home</a></li>
    <li><a href="#academics">Academics</a></li>
    <li><a href="#athletics">Athletics</a></li>
    <li><a href="#contact">Contact</a></li>
</ul>

Upvotes: 2

Views: 15549

Answers (2)

WahhabB
WahhabB

Reputation: 520

A typical way of handling this is to have each page have a class that includes the page name: <div class="academics"> for example.

Now modify your header (within the page div) as follows:

        <ul>
            <li><a class="for_home" href="#home">Home</a></li>
            <li><a class="for_academics" href="#academics">Academics</a></li>
            <li><a class="for_athletics" href="#athletics">Athletics</a></li>
            <li><a class="forcontact" href="#contact">Contact</a></li>
        </ul>

this would be followed by the css as follows:

.home .for_home, .academics .for_academics, .athletics .for_athletics, .contact .for_contact {
  background-color: #EAB126;
}

Then the menu item for the current page will be highlighted.

Congratulations on your first website!

Upvotes: 0

Ahs N
Ahs N

Reputation: 8386

Change this:

a.active
  background-color: #EAB126
}

to this:

li a:focus {
  background-color: #EAB126
}

Here is the JSFiddle demo

This does what you ask BUT if this is a navigation bar then bear in mind that the control will lose focus as soon as you change page. It would be better if you use Javascript/JQuery to handle that much more easily.

Upvotes: 0

Related Questions