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
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/
$("#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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With