Reputation: 97
I want to customize the browser checkbox. When the status is checked, the icon checked.svg
should be displayed instead of checkbox and the icon unchecked.svg
otherwise.
Here is my code. HTML:
<div class="checkbox-custom">
<input type="checkbox"/>
<div class="checkmark">
<img src="@/assets/images/icons/checkbox/unchecked.svg" class="unchecked"/>
<img src="@/assets/images/icons/checkbox/checked.svg" class="checked"/>
</div>
</div>
SASS:
.checkbox-custom {
position: absolute;
width: 28px;
height: 28px;
left: 0;
top: 0;
// Hide default browser checkbox
input[type=checkbox] {
display: none;
}
input[type=checkbox] + .checkmark {
position: absolute;
left: 3.5px;
top: 3.5px;
right: 3.5px;
bottom: 3.5px;
display: inline-block;
cursor: pointer;
img {
width: 21px;
height: 21px;
}
.checked {
display: none;
}
}
input[type=checkbox]:checked + .checkmark {
.checked {
display: block;
}
.unchecked {
display: none;
}
}
}
When i click on the checkbox, nothing happens. What could be the error?
Upvotes: 6
Views: 34410
Reputation: 2841
This can be accomplished without any javascript. Clicking the label element toggles the checkbox inside of it, so with some clever css, we can change the display based on the input's checked state.
input[type=checkbox] {
display: none;
}
.label {
border: 1px solid #000;
display: inline-block;
padding: 3px;
/* background: url("unchecked.png") no-repeat left center; */
/* padding-left: 15px; */
}
input[type=checkbox]:checked + .label {
background: #f00;
color: #fff;
/* background-image: url("checked.png"); */
}
<label><input type="checkbox"><span class="label">Check me</span></label>
Change the .label styles to use background-image of your choice (and position it to the left of your text).
Upvotes: 9
Reputation: 852
CSS:
.checkbox{
width: 23px;
height: 21px;
background: transparent url(https://i.sstatic.net/S4p2R.png ) no-repeat 0 50%
}
.checked{
background: transparent url(https://i.sstatic.net/S4p2R.png ) no-repeat 80% 50%
}
HTML:
<div class="checkbox">
</div>
JQUERY:
$(".checkbox").click(function(){
$(this).toggleClass('checked')
});
This also possible to do with pure JS.
Upvotes: 0