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
button.gridLarge is clicked, I want to highlight it (By adding the class active) and add the class .gridLarge to div.itembutton.grid is clicked, I want to highlight it and add the class .grid to div.itembutton.list is clicked, I want to highlight it and add the class .list to div.itemHere's the code i've so far: JSFiddle
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
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;
}
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