Leader
Leader

Reputation: 97

adding and removing class using jQuery

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:


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

Answers (2)

Sushanth --
Sushanth --

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

Check Fiddle

Upvotes: 0

palaѕн
palaѕн

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

FIDDLE DEMO

Upvotes: 3

Related Questions