Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk
Last active August 29, 2015 14:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mindplay-dk/325842baf3f8c4553d21 to your computer and use it in GitHub Desktop.
Save mindplay-dk/325842baf3f8c4553d21 to your computer and use it in GitHub Desktop.
Replace a checkbox with a custom div for styling

jQuery plugin to replace checkboxes with <div> elements for styling.

This plugin makes no assumptions about class-names or the contents of the <div> element, it only implements the behavior - it returns the generated <div> elements for further operations with jQuery functions, so you can do for example:

$('input[type=checkbox]')
    .checkbox()            // returns set of <div> elements
    .addClass('checkbox')  // adds class="checkbox" to every <div> element
    .html('&#x2714;')      // inserts a unicode checkmark into every <div> element

Example here

/**
* Hides <input type="checkbox"/> and adds an associated <div> element for styling.
*
* Example:
*
* $('input[type=checkbox]').checkbox().addClass('checkbox').html('&#x2714;');
*/
(function () {
function build_checkbox($input, content) {
var div = document.createElement('div');
var $div = $(div);
$input.hide().data('checkbox', div).after($div);
if ($input.prop('checked')) {
$div.addClass('checkbox-checked');
}
$div.on('click', function () {
var checked = !$div.hasClass('checkbox-checked');
$div.toggleClass('checkbox-checked', checked);
$input.prop('checked', checked);
});
$div.on('selectstart dragstart', function (ev) {
ev.preventDefault();
});
return div;
}
jQuery.fn.checkbox = function () {
return $(this).map(function () {
return $(this).data('checkbox')
|| build_checkbox($(this));
});
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment