inputswitch-alt.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. (function( $ ) {
  2. $.fn.simpleCheckbox = function(options) {
  3. var defaults = {
  4. newElementClass: 'switch-toggle',
  5. activeElementClass: 'switch-on'
  6. };
  7. var options = $.extend(defaults, options);
  8. this.each(function() {
  9. //Assign the current checkbox to obj
  10. var obj = $(this);
  11. //Create new span element to be styled
  12. var newObj = $('<div/>', {
  13. 'id': '#' + obj.attr('id'),
  14. 'class': options.newElementClass,
  15. 'style': 'display: block;'
  16. }).insertAfter(this);
  17. //Make sure pre-checked boxes are rendered as checked
  18. if(obj.is(':checked')) {
  19. newObj.addClass(options.activeElementClass);
  20. }
  21. obj.hide(); //Hide original checkbox
  22. //Labels can be painful, let's fix that
  23. if($('[for=' + obj.attr('id') + ']').length) {
  24. var label = $('[for=' + obj.attr('id') + ']');
  25. label.click(function() {
  26. newObj.trigger('click'); //Force the label to fire our element
  27. return false;
  28. });
  29. }
  30. //Attach a click handler
  31. newObj.click(function() {
  32. //Assign current clicked object
  33. var obj = $(this);
  34. //Check the current state of the checkbox
  35. if(obj.hasClass(options.activeElementClass)) {
  36. obj.removeClass(options.activeElementClass);
  37. $(obj.attr('id')).attr('checked',false);
  38. } else {
  39. obj.addClass(options.activeElementClass);
  40. $(obj.attr('id')).attr('checked',true);
  41. }
  42. //Kill the click function
  43. return false;
  44. });
  45. });
  46. };
  47. })(jQuery);