1

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:

  • If one of the <li> is clicked, that particular <li> will be given a new class named "bla" and any other <li> will lose "bla" class.
  • If a <li> which already has "bla" class is clicked, it will lose the "bla" class.
  • if ANYTHING else on the page outside the <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...

2
  • A combination of selectors, addClass / removeClass and a bit of logical thinking might get you on the right path. Try it yourself, and post some updates. It's not that hard. Commented Jul 20, 2013 at 18:02
  • Hahaha... I have looked into the matter for almost 2 hours, yet only managed to find the answer for the first 2 wishes. I have no lead for the last one, which is why I decided to ask the question. Commented Jul 20, 2013 at 18:28

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.