I want to toggle class using jquery If Else statement for specified conditions.
My Html with default css class=\"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)
hi
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