Search code examples
jqueryclassreplaceclassname

Replace part of class name via jquery based on active class


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!


Solution

  • $("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.