Reputation: 97
Searched around the place yet I still couldn't find a solution that I matched my situation. So I decided to ask it myself. Here's what I want to do:
<li>
is clicked, that particular <li>
will be given a new class named "bla" and any other <li>
will lose "bla" class.<li>
which already has "bla" class is clicked, it will lose the "bla" class.<ul>
is clicked, "bla" class will be removed from all the <li>
.The HTML:
<ul>
<li>Item One</li>
<li>Item Two</li>
<li>Item Three</li>
<li>Item Four</li>
</ul>
Thank you...
Upvotes: 1
Views: 917
Reputation: 55750
You can code up something in these lines
// Bind a click event on document
$(document).on('click', function (e) {
// Use e.target to get the element that is currently selected
var $this = $(e.target);
// It item is li or not having a class add it
if (e.target.nodeName === 'LI' && !$this.hasClass('active')) {
$this.addClass('active').siblings().removeClass('active');
} else {
$('li').removeClass('active');
}
});
Upvotes: 0
Reputation: 73976
You can do this:
$('ul > li').click(function () {
$(this).toggleClass('bla').siblings().removeClass('bla');
});
$(document).click(function (e) {
if ($(e.target).closest('ul').length > 0) return;
$('ul > li').removeClass('bla');
});
Upvotes: 3