Under “Customized Html Controls” section I will discuss about how to create and customized standard html controls. This is first article in this category. This will discuss about how we can create a custom checkbox using CSS and jQuery.
Checkbox Image
For this you need two images, one for checked state of checkbox and another for unchecked state of the checkbox. However, you can also use a single image containing both checked and unchecked state and use CSS trick like I use.
Checkbox CSS
Here is the CSS classes we will be going to use for the checkbox
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
checkBox { background-position: 0px 0px; } .checkBoxClear { background-position: -21px 0px; } .checkBox, .checkBoxClear { background-image: url('CheckBox.png'); background-repeat: no-repeat; display: inline-block; float: left; width: 21px; height: 21px; padding: 0px; margin: 0px; cursor: hand; } |
Checkbox JavaScript
Finally below is the JavaScript code using jQuery which will control the checking and un-checking of our checkbox using click event. It will basically toggle the CSS which will change the state.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<script language="javascript" type="text/javascript"> <!-- $(document).ready(function() { $(".checkBox,.checkBoxClear").click(function(srcc) { if ($(this).hasClass("checkBox")) { $(this).removeClass("checkBox"); $(this).addClass("checkBoxClear"); } else { $(this).removeClass("checkBoxClear"); $(this).addClass("checkBox"); } }); }); //--> </script> |
Html Code
Here is a sample Custom Checkbox with the html code.