Home > Web Front-end > CSS Tutorial > How Can I Control Element Visibility in jQuery Beyond `.hide()` and `.show()`?

How Can I Control Element Visibility in jQuery Beyond `.hide()` and `.show()`?

Susan Sarandon
Release: 2024-12-02 15:27:12
Original
219 people have browsed it

How Can I Control Element Visibility in jQuery Beyond `.hide()` and `.show()`?

Achieving Element Visibility with jQuery: Beyond .hide() and .show()

The jQuery .hide() and .show() methods have become quintessential tools for manipulating element visibility based on CSS display settings. However, there may be scenarios where adjusting the display property is not sufficient or desired. To address this need, it is possible to create custom jQuery functions that target the visibility property.

Creating Custom Visibility Functions

To create custom functions that target visibility, we can leverage the .css() method. The following examples demonstrate how to define functions for hiding, showing, and toggling visibility:

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

Overloading the toggle() Function

If a more seamless integration with the existing toggle() function is preferred, it is possible to overload it to handle visibility:

!(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

With these custom functions or overloading techniques, you can now effortlessly manage element visibility using the familiar jQuery syntax without resorting to CSS display settings.

The above is the detailed content of How Can I Control Element Visibility in jQuery Beyond `.hide()` and `.show()`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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