Home >Web Front-end >CSS Tutorial >How Can I Set Visibility to Hidden in jQuery Without Using `display`?

How Can I Set Visibility to Hidden in jQuery Without Using `display`?

Barbara Streisand
Barbara StreisandOriginal
2024-12-08 03:10:14423browse

How Can I Set Visibility to Hidden in jQuery Without Using `display`?

jQuery Equivalent for Setting Visibility to Hidden

In jQuery, the.show() and .hide() methods are commonly used to manipulate the display property and toggle an element's visibility. However, there is no equivalent in-built function to set the visibility property specifically.

Custom Plugin Solution

To address this, you can create your own custom plugins:

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';
    });
};

This allows you to use specific methods like .visible(), .invisible(), and .visibilityToggle() to set or toggle the visibility property.

Overriding jQuery's toggle()

Alternatively, if you prefer to modify the existing toggle() method, you can do the following:

!(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') to toggle the visibility property. However, it's generally not recommended to override built-in methods.

The above is the detailed content of How Can I Set Visibility to Hidden in jQuery Without Using `display`?. 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