I am trying to add a class to a list item when the item is clicked. I did some research and still was unable to add the class properly. thanks!
edit:I am using a masterpage in asp.net
<ul id="menu">
<!-- put class="selected" in the li tag for the selected page - to highlight which page you're on -->
<li><a id="default" href="Default.aspx">Home</a></li>
<li><a id="projects" href="Projects.aspx">Projects</a></li>
<li><a id="blogs" href="Blogs.aspx">Blogs</a></li>
<li><a id="photos" href="Photos.aspx">Photos</a></li>
<li><a id="resume" href="Resume.aspx">Resume</a></li>
<li><a id="contacts" href="Contact.aspx">Contact</a></li>
</ul>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('ul.menu li a').click(function () {
$(this).parent().addClass('selected');
});
});
ul#menu li a:hover, ul#menu li.selected a, ul#menu li.selected a:hover
{ color: #FFF;
background: #1C2C3E url(menu_select.png) repeat-x;}
your selector is incorrect.
ul.menumeans a ul with classmenu.when looking for an id, simply use
$("#menu")also, you may want to take a look at the answers given by @DefyGravity and @Joseph Silber-
they suggest that if you don’t prevent the default click event, the user’s browser would simply follow the link, and the user would never actually see the added class, since they’ll be navigated to a different page.