I’ve been reading recently about how to do Styled Checkboxes. Well, this was something I was working on too – and naturally, I like my way more.
How it works
When the page loads, the JavaScript in checkbox.js checks all of the INPUT tags on the page. If they are a checkbox, and have BOTH and imgOn and an imgOff, then the INPUT tag has its style set to hidden, and the appropriate images are added to the DOM. They’re floating, though, and so are positioned where the checkbox was on the page.
When you click on one, it changes the state of the underlying checkbox (it’s still there, just hidden), and displays the image appropriate for that state.
When the form is submitted, the checkbox is submitted as normal.
As a user leaves the page, on unload the code in checkbox.js tries to tidy up after itself, although I’m a little concerned about memory leaks after some interesting articles I read recently.
Known Issues
- These controls are not part of the tabindex. My friend Bruce Sandeman has been working on a version of this where the images are ‘tabable’, but is struggling to turn the border of the images off. I’ve included the code anyway – see checkbox2.js. I’ve not reviewed it yet, so user beware!
- It’d be nice to hand all events on to the original checkbox for handling.
- At the least, some sort of mouseover/mouseout? It’s not so obvious that these are checkboxes, at least with the demo images I’ve chosen.
- I’m a little concerned about memory leaks given some things I’ve read recently and my use of closures. If anyone knows how to prove/prevent any leaks, let me know, that would be cool
How to Use
Real tricky this – include the checkbox.js file in your HTML page.
<script src="checkbox.js"></script>
Then, in the HTML for each of your checkboxes, add two new attributes – ‘imgOn’ and ‘imgOff’. The value of these attributes should be the path to the images you want to use for the checked (‘on’) and unchecked (‘off’) states.
<input type="checkbox" value='2' imgOn='tick.gif' imgOff='cross.gif' />
and with luck, that should be you done.
See the code below: Continue reading “Styling Checkboxes with JavaScript” →