JSFiddle - React, Tailwind, and code Playground

by mindplay

HTML

<input type="checkbox" name="foo" />
<input type="checkbox" name="bar" checked="checked" />

CSS

.checkbox {
    width: 32px;
    height: 32px;
    line-height: 32px;
    overflow: hidden;
    font-size: 20px;
    color: #ddd;
    transition: color 0.2s;
}

.checkbox-checked {
    color: #080;
}

JavaScript

/**
 * https://gist.github.com/mindplay-dk/325842baf3f8c4553d21
 *
 * Hides <input type="checkbox"/> and adds <div class="checkbox"/> 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));
		});
	};

})();

// EXAMPLE:

jQuery(function ($) {
    
    console.log($('input[type=checkbox]').checkbox().addClass('checkbox').html('&#x2714;'));
    console.log($('input[type=checkbox]').checkbox());
    
});