Reputation: 4302
I have a little project I am working on and I am using jQuery. I tried using a little jQuery to change the class to change some css styles when clicked but it does not seem to work.
heres the important html:
<ul id="UInavList">
<li class="selectedNav"><a href="javascript:;">My Activity</a></li>
<li ><a href="javascript:;">My Tests</a></li>
<li ><a href="javascript:;">Messaging</a></li>
<li ><a href="javascript:;">Search</a></li>
</ul>
and heres the javascript:
$('#UInavList li').click( function() {
$('#UInavList li').removeClass('selectedNav');
$(this).addClass('selectedNav');
})
If you want to see all the code go here: http://jsfiddle.net/chromedude/XXXwL/
Upvotes: 1
Views: 147
Reputation: 185893
One way to go:
$('#UInavList li').click( function() {
$(this).addClass('selectedNav').siblings().removeClass('selectedNav');
});
In order to avoid redundancy-related errors (typos), you could define the class name only once:
$('#UInavList li').click( function() {
var name = "selectedNav";
$(this).addClass(name).siblings().removeClass(name);
});
In this simple case, it seems to not be needed, but if you use the name more than twice, or your handler is more complex, you should consider it.
Upvotes: 2
Reputation: 20602
Your code already works in jsfiddle, you just hadn't set the framework to include jQuery on the right hand side - also with no class set to see the changes, it was hard to tell if it worked.
Look at this demo, it is identical to yours except it has a CSS entry to show up the change and I set the jQuery option on the side.
I would however target the anchor rather than the li
itself and use $(this).closest('li').addClass('selectedNav');
as the second line for preference, remembering to return false if you target an anchor with click() so that the href is not followed.
Upvotes: 2
Reputation: 15835
replace ULNavlist li with this,,it should work
$(this).removeClass('selectedNav');
$(this).addClass('selectedNav');
alert("hello");
Upvotes: 0