Professional checkboxes without framework
With CSS and JavaScript, give your forms a new look.
There are many tutorials showing how to improve the appearance of check boxes, working with jQuery or Mootools or other Ajax framework. But these frameworks are they really necessary in this case?
In fact we can achieve this only with CSS and JavaScript, using the standard form element <button> instead of <checkbox>. And an image to change the look of the box.
Demonstration
To insert a check box on the page, the code is:
<button type="button" class="prettycb" value="0" onclick="setcbimg(this)"></button>
Note that:
1) We use the object <button> and not <input> because the value of the latter is displayed and it is not what we want here. In the case of the button object it is the content between the opening and closing tags that appears.
2) We specify the type "button", it is essential if we want the value attribute managed by browsers (according to our tests).
The CSS code
.prettycb
{
background:url('uncheck.png');
background-repeat:no-repeat;
width:16px;
height:16px;
padding:0;
box-shadow:1px 2x 3px #AAA;
-webkit-box-shadow:1px 2px 3px #AAA;
border:none;
}
The box is initialized as unchecked by the image uncheck.png. This is the default of the code as it is simplified. We can remove it with JavaScript code that initializes the boxes at the page load by changing the image according to the value 0 or 1 of the value attribute.
The JavaScript function
function setcbimg(element)
{
var v = 1 - element.value;
var z = new Image();
if(v)
z.src = "check.png"
else
z.src = "uncheck.png"
element.style.backgroundImage="url(" + z.src + ")";
element.value=v;
}
This function is called when you click on the box, to check or uncheck.
The value in the value attribute is reversed, and according to the new value, is displayed the image of the box checked or not.
This principle allows us to use the form object to store the on/off state, and avoids variables to manage to do so. It is easier to deploy...
Customizing the checkbox
To alter them, just change the two images.
And to manage the problems of alignment of the box with the label on the left, you may add a margin at the top of the image with a transparent background or a CSS code to align the label.
You can use this code as is, if the boxes are all unchecked initially, otherwise you must either add a CSS code for preselected boxes, or create a JavaScript function to initialize the boxes according to their state.
Get rid of JavaScript?
To overcome JavaScript, we must use attribute selectors [type=checkbox] and a pseudoclass :checked, or a second attribute selector, [checked].
But this is not supported by all browsers.
Downloading
Reference