Skip to content

Instantly share code, notes, and snippets.

@nathancarnes
Created June 22, 2012 21:09
Show Gist options
  • Save nathancarnes/2975221 to your computer and use it in GitHub Desktop.
Save nathancarnes/2975221 to your computer and use it in GitHub Desktop.
Use custom checkboxes instead of wonky browser ones
(function($) {
$.fn.fancyCheckboxes = function() {
return this.each(function() {
var input = this;
$(input).hide();
var fancy_checkbox =
$('<span class="fancy_checkbox"/>')
.addClass(
$(input).attr('checked') ? 'checked' : ''
)
.on('click', function(){
$(input).attr('checked') ? $(input).attr('checked', false) : $(input).attr('checked', 'checked');
$(this).toggleClass('checked');
$(input).trigger('click');
});
$(input).after(fancy_checkbox);
});
};
})(jQuery);
@amiel
Copy link

amiel commented Jun 22, 2012

Looks pretty good to me.

Of course, I've always got thoughts. Here are a few:

  1. I've had trouble in the past unchecking checkboxes by setting the checked attribute. The method I've used with success was $(input).removeAttr('checked'). However, this may have changed since I last dealt with that.
  2. You could save a lot of duplication by setting var input = $(this) and changing all instances of $(input) to just input.

@bensonk
Copy link

bensonk commented Jun 22, 2012

Looks handy. I'm with amiel when it comes to setting input = $(this), and avoiding the repeated calls to the jquery wrapper. It cleans things up visually and also saves some cpu cycles. I've had no experience with setting checked attributes programatically, but it does seem like removing the attribute entirely makes the most sense here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment