3

I have a ul menu with three li classes: .1-is-on, .2-is-off, .3-is-off.

Whichever li with the class .active, should show the "on" part of the class name. By default on page load, 1-is-on has .active assigned to it. When I click on 2-is-off .active moves to 2-is-off and leaves 1-is-on, which is great.

As the .active just moved, I want the li where .active is on now to do two things: 1. Replace the "off" part with "on" 2. Replace other "on" from sibling li's with "off"

jQuery:

$(function() {    
$("ul.menu li").bind('click',function() {
   var xxx = $(this).siblings('li:not(.active)')
       if($(this).hasClass('active')) {
        $(this).attr("class",this.className.replace('off','on'));
        $(xxx).attr("class",xxx.className.replace('on','off'));
        }
});
});

HTML:

<ul class="menu">
    <li class="1-is-on active">1</li>
    <li class="2-is-off">2</li>
    <li class="3-is-off">3</li>
</ul>

I hope it's just something small I missed but it's driving me crazy!

2 Answers 2

4
$("ul.menu li").click(function() {
    $(this).siblings().each(function() {
       this.className = this.className.replace("on", "off"); 
    });
    this.className = this.className.replace("off", "on");
    $(this).addClass("active").siblings().removeClass("active");
});

This replaces on with off for all the siblings of the clicked element, then replaces off with on for the clicked element. It then adds the active class to the clicked element and removes it from all others.

You can see an example of this here.

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

Comments

1
$(function() {    
    $("ul.menu li").bind('click',function() {
        // Do nothing if we're already active...
        if ($(this).hasClass('active')) return;

        // find the previously active element, remove active and remove "on"
        var previousOn = $(this).siblings('.active');
        previousOn.removeClass('active');
        previousOn.attr("class", previousOn.attr("class").replace("on", "off"));

        // Make the current element active
        $(this).addClass('active');
        // Replace "off" with "on" for this element
        this.className = this.className.replace('off','on');
    });
});

2 Comments

You're missing the closing parenthesis and semi-colon on the line beginning previousOn.attr(... (and a few other semi-colons).
@james Thanks for that. The semicolons are meh (optional) but the parenthesis would have not been!

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.