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/
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3