Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Custom Styled Checkboxes

4.45/5 (7 votes)
20 Apr 2008MIT11 min read 1   618  
A JavaScript widget to customize the look and feel of check boxes

Custom Styled Checkboxes

The image on the left shows a custom filter bar used in a web application I recently built for a client. This particular web application had a very customized look and feel that utilized allot of custom web widgets, JavaScript, CSS and AJAX. It was allot of fun to work on, but presented many challenges along the way.

Among the several custom web widgets that were built was a custom checkbox control that had the general look seen in this filter bar. (Also seen is a custom 2-way slider control, similar to one found on Bluenile.com which will be the subject of another article.)

The basic operation of the checkbox was as similar to a standard browser-generated checkbox as I could get, but using a more visually appealing look. While modifying standard controls is often not a good idea for usability and accessibility issues, sometimes it is still necessary to achieve a look-and-feel to match the rest of a site. The control described in this article is not meant to be an all-out replacement for the standard checkbox control, nor would I suggest that it is suited to all types of applications. However, you may find uses for it in a number of areas so I am making it publicly available.

What's Supported

Right out of the box, this checkbox widget provides support for most of the typical checkbox functions. The key features are listed below.
  • 2 States (checked, unchecked) (* Note: no support for tri-state check boxes)
  • Enabled / Disabled
  • Mouse support
  • Keyboard support including tab ordering
  • Tooltips
  • Simple grouping
  • Customizable images for the 2 states + enabled/disabled. Images can be customized for the whole page or on a checkbox by checkbox basis, as needed.
  • Works with standard input type=checkbox elements to sync up state.
  • Supports custom event handlers for onMouseOver, onMouseOut, onMouseDown, onMouseUp, onKeyDown.
  • Tested on IE 6, IE 7 and Mozilla FireFox 2.0

How To Use This Widget

There are 4 steps you must perform before you can use the widget. These 4 steps are described below.
1) Add a line to the HEAD section of the web page to reference the JavaScript file for this widget. An example of this is shown below.
<script src="MTGCheckBoxes.js" type="text/javascript"></script>

NOTE: A second JS file named MTGCheckBoxesCompressed.js is included which removes all comments, excess line breaks, etc. from the original JS file. You can substitute this for MTGCheckBoxes.js to conserve some bandwidth.

2) Add a CSS element to your CSS sheet. An example is shown below.
div.MTGCheckBox
{
    background-repeat: no-repeat;
    background-position: top left;
    padding-left: 20px;
    cursor: pointer;
}

NOTE: The class name you use does not need to be MTGCheckBox. It can be whatever name you like. When you initialize the check box widget, you pass in the class name as a parameter.

3) Add the images from the images directory in the download to the images directory of your project/website.

4) Add the MTGCheckBoxes.js and MTGCheckBoxesCompressed.js from the download to the project/website.
There are several ways to make use of this widget. The method you use will depend on how you are building your application, what tools you use, and how you intend to interact with the check boxes. There are 4 basic usage scenarios and I will go through each here.

Method 1: Customize an existing ASP.NET page (or other page that follows the same pattern.)

When ASP.NET generates a checkbox control, the HTML looks something like the example shown below. Other tools may follow a similar pattern. If your HTML looks like the example below, this method can be used.
<input id="CheckBox1" type="checkbox" name="CheckBox1" />
<label for="CheckBox1">ASP.NET CheckBox</label>

Once you have done the 4 steps above, all you need to do is add window.onload event handler to the page or modify the existing one. To add a window.onload event handler, place the following code snippet immediately after the </body> tag.
<script>
window.onload = onLoad;

function onLoad(e)
{
    checkbox_initFromInputs("MTGCheckBox");
}
</script>

If your page already has an onLoad event handler, just add the line below to the bottom of the method.
checkbox_initFromInputs("MTGCheckBox");


* Example 1A shows a simple ASP.NET page before it has been customized with this widget
* Example 1B shows the same ASP.NET page from Example 1A with customization applied


Method 2: Use inline JavaScript to render checkbox objects while the page is rendering

The widget includes a helper method named checkbox_writeNewCheckbox which you can use to directly render a checkbox object into a page by using inline JavaScript.

The checkbox_writeNewCheckbox method has the following prototype.
checkbox_writeNewCheckbox(CSSClassName, NameOfInputElementToWrite, 
   Label, Checked?, [optional] Disabled?, 
   [optional] CustomTooltipText, [optional] GroupName)

Here is a code snippet that demonstrates this technique.
<script language="javascript">
   checkbox_writeNewCheckbox("MTGCheckBox", "abcd1", 
   "Was written in JavaScript and is DISABLED", true, true);
</script>

This method uses document.write to write the HTML for a checkbox. The HTML written includes a hidden input type=checkbox element so that seamless integration with back-end processing can be used (if desired).

* Example 2 shows a simple HTML page that uses inline JavaScript to insert check boxes


Method 3: Insert a checkbox into the page within a pre-defined element

The widget includes a helper method named checkbox_insertNewCheckBox which you can use to insert a checkbox object into the page at a given DOM element.

The checkbox_insertNewCheckBox method has the following prototype.
checkbox_insertNewCheckBox(IDOfElementToInsertAt, CSSClassName, 
   NameOfInputElementToWrite, Label, Checked?, 
   [optional] Disabled?, [optional] CustomTooltipText, 
   [optional] GroupName)

This method creates DOM elements and inserts them into the page as children of the specified element.

Here is a code snippet that demonstrates this technique.
<div id=idInsertedCheckbox></div>
<script>
    checkbox_insertNewCheckBox("idInsertedCheckbox", "MTGCheckBox", 
    "InsertedCheckBox11", 
    "Was inserted into an existing div", true, false, "Tool tip #1");
</script>

* Example 3 shows a simple HTML page that inline JavaScript to insert check boxes at pre-defined points on the page


Method 4: Use server-side code to generate DIV elements of a given class and then allow the widget to customize their appearance

As we've seen from method #1, the widget includes a method named checkbox_initFromDivs that looks for all the DIV elements on the page with a given class name and applies the custom styling to them. With this available method, you can generate HTML on the server using whatever programming tool you want (ASP.NET, ASP, PHP, etc) and allow the widget to stylize the content on the client side.

To use this method, generate HTML that looks like this shown here.
<div class="MTGCheckBox" checked="1">This is my checkbox</div>

And add a window.onLoad event handler lime this.
<script language>
window.onload = onLoad;

function onLoad(e)
{
    checkbox_initFromDivs("MTGCheckBox");
}
</script>


* Example 4 shows a simple generated web page that contains DIV elements and a call to initFromDivs(...);

Customizing the Look and Feel

The widget provides several ways to customize the look and feel of the checkboxes. You can easily apply custom mouseOver and mouseOut event handlers, customize the size, shape and look of the check box images themselves, and customize the positioning of the check box image.

* Example 5 shows how to apply basic mouseover and mouseout customizations

Below is an API reference for the control with a brief description of each method.
checkbox_initFromInputs(strClassName)
Call this method in the window.onLoad event handler to stylize a page that contains ASP.NET style checkboxes.
checkbox_initFromDivs(strClassName)
Call this method in the window.onload event hanlder to stylize a page that contains generated DIV elements (either created using inline JavaScript or server side generated).
checkbox_writeNewCheckbox(strClassName, strName, strLabel, bChecked, bDisabled, strTooltip, strGroup)
Call this method to insert a new checkbox using inline JavaScript. This method will use document.write to insert the new checkbox. When you use this method, you must also call checkbox_initFromInputs(...) in the window.onload event hanlder.
checkbox_insertNewCheckBox(strDivID, strClassName, strName, strLabel, bChecked, bDisabled, strTooltip, strGroup)
Call this method to insert a new checkbox by inserting DOM elements into the page at a given element (as specified by strDivID).
checkbox_checkAll(strGroup, bFireClickEvents)
Call this method to set all the check box objects in a given group (or if strGroup = ""), all check boxes to a checked state.
checkbox_uncheckAll(strGroup, bFireClickEvents)
Call this method to set all the check box objects in a given group (or if strGroup = ""), all check boxes to an unchecked state.
checkbox_sync()
Sometimes other javascript on a page may set the checked attribute of an input element. When this happens, the customized check box objects will not automatically change the background image to represent the change to the user. This method synchronizes the display with the checked state of the hidden INPUT type=checkbox elements.
checkbox_getPostData(bForceReturnUnchecked)
When working on AJAX heavy websites, you may need a way (like I did) to get the post data for all the check boxes on a page. This method will return a string that represents the post data for the checkboxes.
checkbox_setOption_IncludeTabIndexes(bValue)
By default, the widget includes keyboard support and tabbing. Call this method to change this option.
NOTE: Must be called before any widget init or insert functions.
Defaults to TRUE.
checkbox_setOption_PathToImages(strPath)
Changes the default path to where the images are located.
NOTE: Must be called before any widget init or insert functions.
Defaults to "IMAGES/"
checkbox_setOption_EnabledCheckedImageName(strName)
Changes the file name of the image for the Enabled Checked state.
NOTE: Must be called before any widget init or insert functions.
Defaults to "checkbox_EnabledChecked_BlackBox.gif"
checkbox_setOption_EnabledUnCheckedImageName(strName)
Changes the file name of the image for the Enabled UnChecked state.
NOTE: Must be called before any widget init or insert functions.
Defaults to "checkbox_EnabledUnchecked_BlackBox.gif"
checkbox_setOption_DisabledCheckedImageName(strName)
Changes the file name of the image for the Disabled Checked state.
NOTE: Must be called before any widget init or insert functions.
Defaults to "checkbox_DisabledChecked_BlackBox.gif"
checkbox_setOption_DisabledUnCheckedImageName(strName)
Changes the file name of the image for the Disabled UnChecked state.
NOTE: Must be called before any widget init or insert functions.
Defaults to "checkbox_DisabledUnchecked_BlackBox.gif"
checkbox_setOption_ToggleOnMouseUp(bValue)
By default, the widget toggles the checkbox state between checked and unchecked when the user lets the mouse button up, not when it is pressed down. Some people seem to prefer to toggle the checkbox when the mouse button is pressed down, not when let up. When set to FALSE, the checkbox state will be toggled on mouse down events.
NOTE: Must be called before any widget init or insert functions.
Defaults to TRUE.
checkbox_setOption_CustomMouseOverMethod(fnMethod)
The widget can execute a custom OnMouseOver method if desired. The custom function should expect the first parameter to be the DIV object that represents the checkbox.
NOTE: Must be called before any widget init or insert functions.
Defaults to NULL.
checkbox_setOption_CustomMouseOutMethod(fnMethod)
The widget can execute a custom OnMouseOut method if desired. The custom function should expect the first parameter to be the DIV object that represents the checkbox.
NOTE: Must be called before any widget init or insert functions.
Defaults to NULL.
checkbox_setOption_CustomMouseUpMethod(fnMethod)
The widget can execute a custom OnMouseUp method if desired. The custom function should expect the first parameter to be the DIV object that represents the checkbox.
NOTE: The custom function should return TRUE or FALSE. FALSE tells the widget to NOT toggle the checkbox state.
NOTE: Must be called before any widget init or insert functions.
Defaults to NULL.
checkbox_setOption_CustomMouseDownMethod(fnMethod)
The widget can execute a custom OnMouseDown method if desired. The custom function should expect the first parameter to be the DIV object that represents the checkbox.
NOTE: The custom function should return TRUE or FALSE. FALSE tells the widget to NOT toggle the checkbox state.
NOTE: Must be called before any widget init or insert functions.
Defaults to NULL.
checkbox_setOption_CustomKeyDownMethod(fnMethod)
The widget can execute a custom OnKeyDown method if desired. The custom function should expect the first parameter to be the DIV object that represents the checkbox.
NOTE: The custom function should return TRUE or FALSE. FALSE tells the widget to NOT toggle the checkbox state.
NOTE: Must be called before any widget init or insert functions.
Defaults to NULL.

Additional Customizations

In addition to the customization options presented above, there are a few other ways to further customize the look and feel. No examples are provided, but I think a few words will suffice.

  • Set a customOnClickEvent event hanlder on the DIV element. This method should expect the first parameter to be the DIV object. This event handler will be fired when the checkbox state is changed.
  • You can customize the images used on a checkbox-by-checkbox basis by setting the following attributes on the DIV element.
    • cbx_disabledCheckedImage
    • cbx_disabledUnCheckedImage
    • cbx_CheckedImage
    • cbx_UnCheckedImage
  • Place the checkbox on the right by altering the CSS entry to position the background image on the right and use right padding.

Known Issues

This widget does not work with Opera. I don't know why. At this time that is not a priority for me, but if someone can point out the issue, I will try and find time to correct it.

A Word About Customizing Standard Controls

There are allot of usability people who believe that the standard controls (check boxes, radio buttons, list boxes, edit boxes, etc) should not be re-implemented, especially on the web. The reasoning for this is that custom controls rarely support all of the usability and accessibility features of the real ones, are often sensitive to variations on user machines (e.g. themes, localization, etc) and may be harder for users to use. I believe that there is allot of truth in this, and you should not use customized controls without first thinking about who the audience of your application/site will be. However, I do not believe this to be an absolute (otherwise, why would I have created this widget). The standard controls sometimes leave out needed features or styling options. Sometimes an application or site is targeted at a limited audience, not the general population. Other times, the standard controls compete with and detract from the appearance of an app/site. In these unique situations, customizing the custom controls can be very useful.

With that said about usability, probably the greatest reason not to re-implement standard controls is that it takes allot of work to come close to simulating their behavior. Then after you've done the work, you find out that either a) users don't like it, or b) they like it too much and want everything else customized accordingly. Either way, work begets more work. So, be careful with choosing this path.

License

This article, along with any associated source code and files, is licensed under The MIT License