Checkbox and Radio Button Styling
Cross-Browser Checkbox and Radio Button Styling with jQuery
by Modder_
HTML
<h1>jQuery Checkbox and Radio Button Styling</h1>
<div>
<h3>Checkbox:</h3>
<label><input type="checkbox"/> Gorilla</label><br>
<label><input type="checkbox"/> Lamb</label><br>
<label><input type="checkbox"/> Tiger</label>
</div>
<div>
<h3>Radio button:</h3>
<label><input type="radio" name="n"/> Green</label><br>
<label><input type="radio" name="n"/> Blue</label><br>
<label><input type="radio" name="n"/> Orange</label>
</div>
CSS
/*
* customRadioCheck: jQuery plugin for checkbox and radio replacement
* Usage: $('input[type=checkbox], input[type=radio]').customRadioCheck();
* Author: Cedric Ruiz
* License: MIT
*/
.custom-label {
display: inline-block;
/*margin-right: .8em;*/
cursor: pointer;
}
.custom-radio,
.custom-check {
vertical-align: middle;
display: inline-block;
position: relative;
top: -.15em; /* Adjust to for best fit */
/*margin: 0 .4em;*/
width: 20px;
height: 20px;
background: url('http://www.1stwebmagazine.com/demo/img/customRadioCheck.png') 0 0 no-repeat;
}
.custom-radio { background-position: 0 -20px; }
.custom-check.focus { background-position: -20px 0; }
.custom-radio.focus { background-position: -20px -20px; }
.custom-check.checked { background-position: -40px 0; }
.custom-radio.checked { background-position: -40px -20px; }
.custom-check.checked.focus { background-position: -60px 0; }
.custom-radio.checked.focus { background-position: -60px -20px; }
JavaScript
/*
* customRadioCheck: jQuery plguin for checkbox and radio replacement
* Usage: $('input[type=checkbox], input[type=radio]').customRadioCheck();
* Author: Cedric Ruiz
* Modifier: Alexander Kravchenko <modder.modding@gmail.com>
* License: MIT
*/
;(function($){
$.fn.customRadioCheck = function() {
return this.each(function() {
var $this = $(this);
var $span = $('<span/>');
var type = $this.is(':checkbox') ? 'check' : ($this.is(':radio') ? 'radio' : '');
if ( ! type) return;
$span.addClass('custom-'+ type);
$this.is(':checked') && $span.addClass('checked'); // init
$span.insertAfter($this);
$this.parent('label').addClass('custom-label')
.attr('onclick', ''); // Fix clicking label in iOS
// hide by shifting left
$this.css({ position: 'absolute', left: '-9999px' });
// Events
$this.on({
change: function() {
if (type === 'radio') {
var $elem = $this.closest('form');
if ($elem.length) {
$elem = $elem.find('input[name="' + $this.attr('name') + '"]:radio');
} else {
$elem = $('input[name="' + $this.attr('name') + '"]:radio').filter(function() {
return ! $(this).closest('form').length;
});
}
$elem.next(".custom-radio").removeClass('checked');
}
$span.toggleClass('checked', $this.is(':checked'));
},
focus: function() { $span.addClass('focus'); },
blur: function() { $span.removeClass('focus'); }
});
});
};
}(jQuery));
$('input[type=checkbox], input[type=radio]').customRadioCheck();