Created
February 5, 2012 19:16
-
-
Save erikig/1747510 to your computer and use it in GitHub Desktop.
jquery.toggler.js - A jQuery plugin that allows checkboxes or radio input with class="{name}_toggle" to toggle elements with class="{name}"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* jquery.toggler.js | |
* - Allows checkboxes or radio input with class="{name}_toggle" to toggle elements with class="{name}" | |
* - Handles click event and pre-populated form fields | |
* | |
* Implementation Detail: | |
* 1. Include jquery & jquery.toggler.js | |
* 2. Call $('input[type="checkbox"][class$="_toggle"]').toggler(); | |
* 3. ???? | |
* 4. Profit! | |
* | |
* Released to public domain, comments welcome. | |
* | |
**/ | |
(function( $ ) { | |
var methods = { | |
init : function(){ | |
return this.each(function(){ | |
var $this = $(this); | |
$this.on('click',methods.click); | |
return methods.tgl($this); | |
}); | |
}, | |
destroy : function(){ | |
return this.each(function(){ | |
$this = $(this); | |
$this.off('click',methods.click); | |
}); | |
}, | |
click : function(){ | |
var $this = $(this); | |
if($this.is(':radio')){ | |
input_name = $this.attr('name'); | |
$('input[name='+ input_name + ']:radio').each(function(input_index,input_element){ | |
methods.tgl($(input_element)); | |
}); | |
} else { | |
methods.tgl($this); | |
} | |
}, | |
tgl : function($this){ | |
var class_list = $this.attr('class').split(/\s+/); | |
var is_checked = $this.is(':checked'); | |
$.each( class_list, function(class_index, class_item){ | |
if (class_item.indexOf("_toggle") > 0) { | |
var toggleClass = "." + class_item.replace("_toggle", ""); | |
if(is_checked) { | |
$(toggleClass).show(); | |
} else { | |
$(toggleClass).hide(); | |
} | |
} | |
}); | |
} | |
}; | |
$.fn.toggler = function(method) { | |
if ( methods[method] ) { | |
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 )); | |
} else if ( typeof method === 'object' || ! method ) { | |
return methods.init.apply( this, arguments ); | |
} else { | |
$.error( 'Method ' + method + ' does not exist' ); | |
} | |
}; | |
})( jQuery ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment