0

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;}

user516883
  • 8,868
  • 23
  • 72
  • 114

4 Answers4

7

your selector is incorrect. ul.menu means a ul with class menu.
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.

J. Ed
  • 6,692
  • 4
  • 39
  • 55
  • sJhonny was first, +1, highly recommend the prevent default. Optionally, remove the 'selected' class from the sibling
  • 's.
  • – DefyGravity Aug 15 '11 at 17:22
  • How would can you change the page then? – user516883 Aug 15 '11 at 17:29
  • you should add your 'selected' class on load (and not when clicking a link), based on the current page that you're on. see the accepted answer here: http://stackoverflow.com/questions/6690930/how-to-manipulate-on-document-ready-elements-which-were-created-on-document-rea – J. Ed Aug 15 '11 at 17:49