Reputation: 17372
I want to set an attribute class="active"
upon selection of a particular list. For eg when a a particular list is active, it should get active & when other is selected, that list should get active.
My current jQuery code sets all list as active upon selection of any item from the list. Instead i want only that item should be active which is selected.
How do I modify my jQuery code?
<ul class="nav nav-pills nav-stacked span5">
<li class = "list"><a href="#" class="span3">abc</a></li>
<li class = "list"><a href="#" class="span3">def</a></li>
<li class = "list"><a href="#" class="span3">ghi</a></li>
<li class = "list"><a href="#" class="span3">jkl</a></li>
</ul>
jQuery
$(document).ready(function () {
$(".span3").click(function () {
$('.list').attr("class","active"); // sets all the list item active. Instead I want only that particular element to be active.
});
});
Upvotes: 0
Views: 876
Reputation: 2308
Jquery provides more functions. That nobody is using.
Jquery Code:
$(document).ready(function () {
$(".nav>li").click(function () {
$(this).siblings('.active').toggleClass("active");
$(this).toggleClass("active");
});
});
Link : http://jsfiddle.net/techsin/hJYfu/3/ NEW
Pay attention to html structure.
Upvotes: 1
Reputation: 972
Use addClass method instead of attr
$(document).ready(function () {
$(".span3").click(function () {
$('.list').removeClass('active');
$(this).parent().addClass("active");
});
});
Upvotes: 0
Reputation: 6694
You can add class with this one:
$(document).ready(function () {
$(".span3").click(function () {
$(this).parent().addClass("active");
});
});
and for remove class like this:
$(document).ready(function () {
$(".span3").click(function () {
$('.list').removeClass("active");
});
});
See this in jQuery API Document addClass() and removeClass()
UPDATE:
Yep, i forget the parent()
Upvotes: 1
Reputation: 824
Use $(this).parent()
to get only the clicked on list
, and it's easier to use addClass
instead of attr
.
$(document).ready(function () {
$(".span3").click(function () {
$(this).parent().addClass("active");
});
});
If you want all of the other lists to not be active as well:
$(document).ready(function () {
$(".span3").click(function () {
$('.list').removeClass("active");
$(this).parent().addClass("active");
});
});
Upvotes: 3