A common operation I find myself doing is the following:
<ul>
<li>One</li>
<li class="current">Two</li>
<li>Three</li>
</ul>
var $allLi = $('li');
$allLi.click(function(){
$allLi.removeClass('current');
$(this).addClass('current');
});
Is there a way to condense this, somehow by combining $allLi and $(this) and using toggleClass?
Thanks!
Jonathan's solution should work just fine but I would like to propose a different solution.
Rather than unsetting all the elements and then selecting the current one, why not just keep track of the current element and only perform the operation on that?
<ul>
<li>One</li>
<li class="current">Two</li>
<li>Three</li>
</ul>
<script type="text/javascript">
(function () {
var current = $("li.current");
$("li").click(function () {
current.removeClass("current");
current = $(this);
current.addClass("current");
});
}());
</script>
It's "longer" but also more efficient.
My solution aims to have all state in JavaScript rather than partly in the DOM. toggleClass
circumvents this principle. It's not so much a matter of "hey looks this a really long and super complex way of doing something simple", there's an idea behind it. If your application state gets more complex than just one selected element you'll run into issues if you try and stuff that state into the DOM. The DOM is just a 'view', keep your state in the 'model' (the JS code).
I believe you could add it, and remove it from the siblings:
$("li").on("click", function(){
$(this)
.addClass("current")
.siblings()
.removeClass("current");
});
Demo: http://jsbin.com/owivih/edit#javascript,html,live
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With