when the user clicks on a menu tab i want it to remain selected with it a white button.
here is my attempt but its not working. if you click the home button it does
I see several modifications here.
Firstly, when you apply selected class, you are applying to all li
items, which is not true. you only want to apply the class to clicked list item.
secondly, when you click another list item, you want to remove the selected class.
so the code modified would be:
$('#navigation li').click(function() {
$('#navigation li').removeClass('selected');
$(this).addClass('selected');
});
Most importantly, you do not have a selected
class. I put a temporary selected class definition like so:
.selected{
border: 1px solid #888;
background-color: #white;
}
You can see a working example here: on JsFiddle
additionally, your a
element has a gray background. so you might want to apply selected white background class to your a element also.. something like:
$('a', this).addClass('selected'); //apply to anchor element also
and when you remove the class, follow the same deal.
So you want to persist the button states across different Pages. Javascript is only valid as long as the page is open. As soon as the user goes to the new page, all javascript will be reset. To overcome this you can do one of these two things:
1) If you are using a master page for menu, add runat="server"
attribute to your list items, and from code behind, add selected class to appropriate list item from your child page (may be you could have a public function in your Master page)
//Master page
public SetHomeMenu()
{
liHome.Attributes.Add("class","selected");
}
//in Child page
Master.SetHomeMenu();
2) If you want to do it in javascript, you need to read your url, parse it, then add selected
class to appropriate li
//put this javascript in your head section or even at the bottom, just before closing
// body tag
$(document).ready(function () { if(window.location.href.indexOf("home")) { $("#navigation li#home").addClass("selected"); } else if(window.location.href.indexOf("about")) { $("#navigation li#about").addClass("selected"); } else if(window.location.href.indexOf("contact")) { $("#navigation li#contact").addClass("selected"); } });
But for this to work, you need to add id
attributes to your list items like so:
For use the last solution you need to change the if statement to this example:
if(window.location.href.indexOf("home") > -1)