Reputation: 334
I am currently trying to design a navigation bar for one of my websites. This navigation bar will be across the top of the webpage.
The problem is that I can get the items to change colour when I hover over them, but cannot get the items to stay in the hover state once the page is active. So for example, if I wanted to go "Home", I would hover over the "Home" item in the navigation bar, and it would turn gray, when I click on it to go back to "index.php" the "Home" in the navigation bar would stay gray. (With the background of the navigation bar being black).
I have formatted a table with a single row, and a few pieces of data, which will serve as links. This is what the HTML code kind of looks like:
<div id="header_banner">
<table id="header_banner_table">
<tr id="header_banner_row">
<td id="header_banner_a"><a class ="link1" href="">Item 1</a></td>
<td id="header_banner_b"><a class ="link1" href="">Item 2</a></td>
<td id="header_banner_c"><a class ="link1" href="">Item 3</a></td>
<td id="header_banner_d"><a class ="link1" href="">Item 4</a></td>
<td id="header_banner_e"><a class ="link1" href="">Item 5</a></td>
<td id="header_banner_f"><a class ="link1" href="">Item 6</a></td>
<td id="header_banner_g"><a class ="link1" href="">Item 7</a></td>
</tr>
</table>
</div>
Here is some of the CSS:
#header_banner {
display: block;
position: fixed;
top: 0px;
left: 0px;
right: 0px;
width: 100%;
height: 71px;
background-color: black;
color: white;
font-size: 18px;
text-align:center;
text-transform: uppercase;
text-decoration: none;
}
#header_banner_table {
position: fixed;
top: 0px;
width: 60%;
padding: 0px;
margin-left: 20%;
margin-right: 20%;
}
.link1 {
position: relative;
display: block;
color: white;
text-decoration: none;
padding-top: 23px;
padding-bottom: 23px;
padding-left: 20px;
padding-right: 20px;
}
.link1:hover{
position: relative;
display: block;
text-decoration: none;
color: white;
padding-top: 23px;
padding-bottom: 23px;
padding-left: 20px;
padding-right: 20px;
background-color: gray;
}
So currently the background of the navigation bar is black, and when you hover over something, it turns gray. I would like it to stay gray when that page is active.
Any solutions?
Thank you in advance.
Upvotes: 1
Views: 3560
Reputation: 661
Are you familiar with jQuery? If I'm thinking the same thing as you are you should be able to do it with jQuery.
var path = window.location.pathname;
$('#header_banner_row a').each(function(){
if( $(this).attr('href') === path ){
$(this).addClass('active');
}
});
So basically, var path
is whatever is after .com in the navigation bar in your browser. And if that path is the same as one of the a
in the header, it will get a class of active that you can style to be gray.
Upvotes: 1