Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use removeClass and addClass by click button

Tags:

jquery

css

I want to highlight a button once it's clicked and add a particular class to a <div> having class item as well.

HTML

<button type="button" class="btn gridLarge">largegrid</button>
<button type="button" class="btn grid active">smallgrid</button>
<button type="button" class="btn list">list</button>
<div class="item">text</div>

CSS

.item{
   height:240px;
   border:1px solid orange;
 }
.item.list{
   width:600px;
   height:500px;
   border:1px solid red;
 }
 .item.gird{
   width:400px;
   height:500px;
   border:1px solid red;
 }
.item.gridlarge{
   width:500px;
   height:500px;
   border:1px solid red;
}

button{
  cursor:pointer;
  border:1px solid green;
   padding:20px;
  color:red;
  margin-bottom:20px;
 }

.btn.active{
  color:green;
  background-color:red;
}

for example

  1. When button.gridLarge is clicked, I want to highlight it (By adding the class active) and add the class .gridLarge to div.item
  2. When button.grid is clicked, I want to highlight it and add the class .grid to div.item
  3. When button.list is clicked, I want to highlight it and add the class .list to div.item

Here's the code i've so far: JSFiddle

like image 980
JavaEagle Avatar asked Feb 06 '26 16:02

JavaEagle


2 Answers

If you apply the class to be added as the id for buttons, you can do the following:

$('.btn').click(function(){
  $('.active').removeClass('active');
  $(this).addClass('active');
  $('.item').removeClass().addClass('item').addClass(this.id);
});

Demo

side note: you had a typo in your css, the class in second button is grid, in css its gird

like image 135
T J Avatar answered Feb 09 '26 11:02

T J


You can get class by attr and then remove btn class to get other class names. But, I would prefer to save class names in data attribute.

Demo

HTML:

<button type="button" data-class="gridLarge" class="btn gridLarge active">largegrid</button>
<button type="button" data-class="grid" class="btn grid">smallgrid</button>
<button type="button" data-class="list" class="btn list">list</button>
<div class="item"></div>

Javascript:

$('.btn').click(function () {
    var $this = $(this);

    $('.btn').removeClass('active');
    $this.addClass('active');

    $('.item').removeClass('gridLarge grid list').addClass($this.data('class'));
});

CSS:

.item {
    height:240px;
    border:1px solid orange;
}
.item.list {
    width:600px;
    height:500px;
    border:1px solid red;
}
.item.grid {
    width:400px;
    height:500px;
    border:1px solid red;
}
.item.gridlarge {
    width:500px;
    height:500px;
    border:1px solid red;
}
button {
    cursor:pointer;
    border:1px solid green;
    padding:20px;
    color:red;
    margin-bottom:20px;
}
.btn.active {
    color:green;
    background-color:red;
}
like image 28
Jashwant Avatar answered Feb 09 '26 12:02

Jashwant