Home >Web Front-end >CSS Tutorial >How Can I Create jQuery Functions to Control CSS Visibility?

How Can I Create jQuery Functions to Control CSS Visibility?

Susan Sarandon
Susan SarandonOriginal
2024-11-29 18:07:101041browse

How Can I Create jQuery Functions to Control CSS Visibility?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn