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
Release: 2024-11-29 18:07:10
Original
1060 people have browsed it

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

Example usage:

$('#element').visible(); // Makes element visible
$('#element').invisible(); // Makes element invisible
$('#element').visibilityToggle(); // Toggles visibility
Copy after login

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);
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template