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!

Wonka
  • 8,244
  • 21
  • 73
  • 121

2 Answers2

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.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
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');
    });
});
Philip Ramirez
  • 2,972
  • 1
  • 16
  • 16