Creating jQuery Functions to Manipulate CSS Visibility
In jQuery, the .hide() and .show() methods conveniently set the CSS display property to none and block, respectively. However, is there a similar function that explicitly sets the CSS visibility property to hidden?
Solution
While jQuery doesn't provide a native function specifically for setting visibility, you can easily create your own.
Creating custom visibility functions:
jQuery.fn.visible = function() { return this.css('visibility', 'visible'); }; jQuery.fn.invisible = function() { return this.css('visibility', 'hidden'); }; jQuery.fn.visibilityToggle = function() { return this.css('visibility', function(i, visibility) { return (visibility == 'visible') ? 'hidden' : 'visible'; }); };
Example usage:
$('#element').visible(); // Makes element visible $('#element').invisible(); // Makes element invisible $('#element').visibilityToggle(); // Toggles visibility
Overloading the native toggle() function (not recommended):
!(function($) { var toggle = $.fn.toggle; $.fn.toggle = function() { var args = $.makeArray(arguments), lastArg = args.pop(); if (lastArg == 'visibility') { return this.visibilityToggle(); } return toggle.apply(this, arguments); }; })(jQuery);
This allows you to use toggle('visibility') as a shortcut for toggling the visibility. However, this is not generally recommended as it can override the default behavior of toggle() in other contexts.
Interactive jsFiddle Demonstration:
https://jsfiddle.net/
The above is the detailed content of How Can I Create jQuery Functions to Control CSS Visibility?. For more information, please follow other related articles on the PHP Chinese website!