Reputation: 1598
I am exploring a way to to change the background colour of div OR change its class when a select box is checked. I can't figure it out because I can't understand what the best approach would be. I have replicated what I have done here: https://jsfiddle.net/c8qremy2/
<input type="checkbox" name="blue" value=".cp" id="cp"><label for="blue">Couch Potato</label>
So by checking the above checkbox is it possible to change the background colour of the below div:
<div class="item cp sp cf bb" id="launDroid">
<a href="" class="bgRed">
<div class="content">
<h2>Laundroid</h2>
<p>Laundry That Does Itself</p>
<div class="tileFooter">Category</div>
</div>
</a>
</div>
The background colour belongs to the to bgRed class. I am wondering if the above checkbox is selected it can change the bgRed class to say bgBlack which would be a black background?
Upvotes: 0
Views: 60
Reputation: 83
What you will need to do is set a watch for when the toggle is changed and then check whether or not the property is checked. You can do this with jQuery. I have updated the jsfiddle here: https://jsfiddle.net/c8qremy2/2/
Also refer to this question here to see how to check if a checkbox is checked with jQuery: How to check whether a checkbox is checked in jQuery?
The jQuery (this makes the checkbox toggle the bg from black to white):
$('#cp').click(function() {
if($('#cehcekc').prop('checked')) {
$('.bgRed').css('background-color','#000');
} else {
$('.bgRed').css('background-color','#fff');
}
});
Upvotes: 1
Reputation: 53664
You can monitor the change
event and update the rest of the DOM as you see fit. Also, the for
attribute on your label should be the id
of the input
you want it to apply to, not the name
attribute.
$('#cp').on('change',function() {
if ($(this).is(':checked')) {
$('.bgRed').addClass('bgBlack');
} else {
$('.bgRed').removeClass('bgBlack');
}
})
.item {
width: 300px;
height: 300px;
margin: 0px;
float: left;
position: relative;
background-position: center;
background-repeat: no-repeat;
background-size: 100%;
}
.item a{
height: 100%;
width: 100%;
position: absolute;
}
.item:hover a.bgRed{
background-color: rgba(232,43, 71, 0.9);
}
.item:hover a.bgBlack {
background: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item cp sp cf bb" id="launDroid">
<a href="" class="bgRed">
<div class="content">
<h2>Laundroid</h2>
<p>Laundry That Does Itself</p>
<div class="tileFooter">Category</div>
</div>
</a>
</div>
<input type="checkbox" name="blue" value=".cp" id="cp"><label for="cp">Couch Potato</label>
Upvotes: 1
Reputation: 2837
Yes, jQuery can remove a class and replace it with another class:
$('a').removeClass('bgRed').addClass('bgBlack');
Upvotes: 1