Skip to content

Instantly share code, notes, and snippets.

@rjz
Created May 6, 2011 20:48
Show Gist options
  • Save rjz/959753 to your computer and use it in GitHub Desktop.
Save rjz/959753 to your computer and use it in GitHub Desktop.
Checkbox replacement example
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script type="text/javascript">
/**
* Demo for replacing checkboxes with a custom element using jQuery
*
* @author RJ Zaworski <rj.zaworski@gmail.com>
*/
;(function($){
/**
* Replace checkbox with a styleable div.
*
* @param class the class name to apply to the new div
*/
$.fn.autoCheckbox = function(settings){
// set up default settings
var o = $.extend({
class: 'my_custom_box'
}, settings || {});
$(this).each(function(){
// get the original checkbox
$this = $(this);
// create the replacement div
$('<div class="unchecked"></div>')
.addClass(o.class)
.click(function(){
// pass click event back to the original checkbox
$this.click()
// update the div's class to reflect the current state
$(this).removeClass('checked').removeClass('unchecked').addClass( $this.is(':checked') ? 'checked' : 'unchecked' );
})
.insertAfter($this);
// hide the original div
$this.hide();
});
}
// kickstart when the app begins
$(document).ready(function(){
$('input[type=checkbox]').autoCheckbox({class:'fauxbox'});
}) // document.ready
})(jQuery);
</script>
<style type="text/css">
/**
* Some default styling for our new checkbox elements. We'll need to style
* two states -- when the box is checked (.checked) and when it isn't
* (.unchecked). For both states, we'll need both a default appearance and
* an appearance that's used when the checkbox is being hovered over/focused
* on. Here goes nothing:
*/
.fauxbox {
width:30px;
height:30px;
display:inline-block;
border:1px solid #ccc;
cursor:pointer;
}
.fauxbox.checked {
background-color:#0f0;
}
.fauxbox.checked:hover,
.fauxbox.checked:focus {
background-color:#5f5;
}
.fauxbox.unchecked {
background-color:#fff;
}
.fauxbox.unchecked:hover,
.fauxbox.unchecked:focus {
background-color:#cfc;
}
</style>
</head>
<body>
<form>
<input type="checkbox" name="checkbox" value="" />
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment