Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Toggle/cycle through 3 state

I have a button, which i need to run through 3 state. eg: Mute, On and Off

<html>
  <head>
     <!-- define mute/on/off styles -->
     <style type="text/css">
      .mute{ background:gray }
      .on  { background:green }
      .off { background:red }
     </style>

     <!-- define the toggle/cycle function -->
     <script language="javascript">
        function toggleState(item){
        if(item.className == "mute") {
              item.className="on";
           } else if(item.className == "on") {
              item.className="off";
           } else {
              item.className="mute";
           }
        }
     </script>
  </head>
  <body>
     <!-- call 'toggleState' whenever clicked -->
     <input type="button" id="btn" value="button" class="mute" onclick="toggleState(this)" />
  </body>
</html>

How can i cycle through this using jQuery rather using plain JavaScript

like image 748
Syed Avatar asked Jan 14 '23 21:01

Syed


2 Answers

Try this:

var classNames = ['mute','on','off'];
$('div').click(function () {
    $(this).toggleClass(function (i, className, b) {
        var index = (classNames.indexOf(className) + 1) % classNames.length;
        $(this).removeClass(className);
        return classNames[index];
    });
});

In this code, className is the old class. Then get the new class through classNames array, then return it.

And before return, the old class should be removed.

And with this method, you can easily expand 3 to any larger number.

Here is jsfiddle. http://jsfiddle.net/f3qR3/2/


Another situation

If there are other classes in the element, you can use the following code, but it is more complicated.

var classNames = ['mute', 'on', 'off'];
$('div').click(function () {
    var $this = $(this);
    $this.toggleClass(function (i, className, b) {
        var ret_index;
        $.each(classNames, function (index, value) {
            if ($this.hasClass(value)) {
                ret_index = (index + 1) % classNames.length;
            }
        });
        $this.removeClass(classNames.join(' '));
        return classNames[ret_index];
    });
});

Here is jsfiddle. http://jsfiddle.net/f3qR3/4/

like image 124
pktangyue Avatar answered Jan 19 '23 11:01

pktangyue


$("#btn").click(function(
var this=$(this);
if(this.hasClass('mute')) {
              this.removeClass("mute").addClass("on");
           } else if(this.hasClass('on')) {
              this.removeClass("on").addClass("off");
           } else {
              this.removeClass("off").addClass("mute");
           }
        }
});

You don't need to add any onclick function, just placed it under jquery ready() function.

like image 20
Sudip Pal Avatar answered Jan 19 '23 10:01

Sudip Pal