I want to toggle class using jquery If Else statement for specified conditions.
My Html with default css class=\"horizontal\"
You can use the switch in toggleClass().
A Boolean value to determine whether the class should be added or removed.
$('#foo-bar').toggleClass('horizontal', myvar==layout1)
.toggleClass('vertical', myvar==layout2);
There is a toggleClass method that does this; it even works with multiple class names separated by spaces. So toggle both of them, no matter what's the current class of the element:
$("#foo-bar").toggleClass("horizontal vertical");
You can use toggleClass
Live Demo
Html
<div id="foo-bar" class="horizontal"> </div>
Javascript
$('#foo-bar').toggleClass('vertical');
In case you do not want to use the toogleClass(), here is another solution:
http://jsfiddle.net/YFBWQ/
$('#foo-bar')
.removeClass('horizontal vertical')
.addClass( myvar=='layout2' ? 'vertical' : 'horizontal')
or
$('#foo-bar')
.removeClass(myvar=='layout2' ? 'horizontal' : 'vertical')
.addClass(myvar=='layout2' ? 'vertical' : 'horizontal')
simple case:
var vh = "layout1";
$('#foo-bar').addClass(function () {
$(this).prop('class', '');
return vh == 'layout1' ? 'horizontal' : 'vertical';
});
EDIT ADDED: definative simple case sets it to no classes if none match
var vh = "layout9";
$('#foo-bar').prop('class',function () {
return vh == 'layout1' ? 'horizontal' : (vh == "layout2" ? 'vertical' : (vh=="layout3" ? "reddy" : ""));
});
more complex case:
var vh1 = "layout2";
var classList = $('#foo-bar').prop('class').split(/\s+/);
$('#foo-bar').addClass(function (vh1) {
var self = this;
$.each(classList, function (index, item) {
//IF you want to keep one, check it here
if (item != "keepme") {
$(self).removeClass(item);
}
});
switch (vh1) {
case "layout1":
return "horizontal";
case "layout2":
return "vertical";
default:
return "reddy";
}
});
EDIT2: leave the classes alone if none match! (caution, replaces all classes with new set)
<div id="foo-bar" class='reddy3 freddy' >hi</div>
keep existing:
var vh = "nomatches";
$('#toggle').prop('class',function (i,v) {
return vh == 'layoutA' ? 'horizontal' : (vh == "layout2" ? 'vertical' : (vh=="layout3"? "reddy":v));
});// keeps "reddy3 freddy"
set multiple:
var vh = "greenhorizontal";
$('#toggle').prop('class',function (i,v) {
return vh == 'layout2' ? 'horizontal' : (vh == "layout2" ? 'vertical' : (vh=="greenhorizontal"? "greeny horizontal":v));
});//sets both "greeny" and "horizontal", wipes out existing
FYI, substitue your "myvar" for vh and vh1 for full solution