Skip to content

Instantly share code, notes, and snippets.

@rafaelrinaldi
Created February 24, 2014 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafaelrinaldi/9196582 to your computer and use it in GitHub Desktop.
Save rafaelrinaldi/9196582 to your computer and use it in GitHub Desktop.
Simple jQuery plugin to toggle between shown/hidden states.
/**
* Simple jQuery plugin to toggle between shown/hidden states.
*
* Markup:
*
* <div class='box' style='width: 50px; height: 50px; background: red; padding: 20px;'>Box</div>
* <button>Toggle</button>
*
* Usage:
*
* // The box will toggle its visibility every time user clicks on `button`.
* $('button').click(function() {
* $('.box').visibilityToggle();
* });
*/
(function($) {
$.fn.visibilityToggle = function() {
var context = $(this),
isHidden = context.css('display') === 'none';
if(isHidden) {
context.show();
} else {
context.hide();
}
};
})(jQuery);
@rafaelrinaldi
Copy link
Author

Turns out that using the native toggle() method without any parameters will toggle visibility.

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