jQuery addClass example
Change class name on click in jQuery
by josekerekes
HTML
<div class="box col-lg-6 col-md-6 col-sm-12 col-xs-12">
box1box1box1box1box1box1box1box1box1box1box1box1box1box1box1box1box1box1
</div>
<div class="box col-lg-4 col-md-4 col-sm-12 col-xs-12">
box2</div>
<div class="box col-lg-4 col-md-4 col-sm-12 col-xs-12">
box3
</div>
<div class="box col-lg-4 col-md-4 col-sm-12 col-xs-12">
box4box4box4box4box4box4box4box4box4box4box4box4box4
</div>
<div class="box col-lg-4 col-md-4 col-sm-12 col-xs-12">
box5box5box5box5box5box5box5box5box5box5box5box5box5
</div>
CSS
* {
}
.box {
background:#ccc;
float:left;
overflow:hidden
}
.col-xs-12 {
width:100%
}
.col-lg-4 {
width:33.3333%
}
.col-lg-6 {
width:50%;
}
.col-lg-8 {
width:66.6666%
}
JavaScript
var items = $('.box');
var twoThirds = "col-lg-8 col-md-8 col-sm-12 col-xs-12";
var fullCol = "col-xs-12";
$.fn.deColumnize = function() {
return this.each(function() {
});
}
items.each(function() {
if (this.scrollWidth > Math.ceil($(this).innerWidth())) {
this.style.background = "red";
if($(this).prev('.box').hasClass('col-lg-4')){
$(this).removeClass(function (index, className) {
return (className.match(/col-[a-z]{2}-([0-9]{1,2})?/g) || []).join(' ');
}).addClass(twoThirds).addClass('paired');
}
else {
if($(this).prev('.box').length) {
$(this).prev('.box').not('.paired').removeClass(function (index, className) {
return (className.match(/col-[a-z]{2}-([0-9]{1,2})?/g) || []).join(' ');
}).addClass(fullCol);
}
if(!$(this).next('.box').hasClass('col-lg-4')){
$(this).removeClass(function (index, className) {
return (className.match(/col-[a-z]{2}-([0-9]{1,2})?/g) || []).join(' ');
}).addClass(fullCol);
}
else {
$(this).removeClass(function (index, className) {
return (className.match(/col-[a-z]{2}-([0-9]{1,2})?/g) || []).join(' ');
}).addClass(twoThirds);
}
}
}
});