jQuery jQuery Tutorial jQuery Effects jQuery HTML jQuery Traversing jQuery AJAX jQuery Misc



jQuery Hide/Show

jQuery is a popular JavaScript library that simplifies the process of creating dynamic and interactive web pages. One of the most commonly used features of jQuery is the ability to hide and show elements on a web page. This feature is particularly useful for creating interactive user interfaces and for controlling the visibility of content on a web page.

Brief Explanation of jQuery Hide/Show

The jQuery hide() and show() methods are used to control the visibility of elements on a web page. The hide() method is used to hide an element, while the show() method is used to display an element that has been hidden. These methods can be used to create interactive user interfaces, such as drop-down menus, pop-up windows, and accordions.

The hide() and show() methods can be used with a variety of CSS properties, including display, visibility, and opacity. By default, the hide() method sets the display property of an element to "none", while the show() method sets the display property to its default value (which is usually "block" or "inline").

Code Examples

Here are some examples of how to use the hide() and show() methods in jQuery:

Example 1: Hide and Show a Div Element

HTML:

<div id="myDiv">
  <p>This is some text.</p>
</div>

jQuery:

$(document).ready(function(){
  $("#myDiv").hide();
  $("#myDiv").show();
});

In this example, the hide() method is used to hide the "myDiv" element, and the show() method is used to display it again.

Example 2: Toggle the Visibility of a Div Element

HTML:

<div id="myDiv">
  <p>This is some text.</p>
</div>

<button id="myButton">Toggle</button>

jQuery:

$(document).ready(function(){
  $("#myButton").click(function(){
    $("#myDiv").toggle();
  });
});

In this example, the toggle() method is used to toggle the visibility of the "myDiv" element when the "myButton" button is clicked.

Example 3: Slide Up and Down a Div Element

HTML:

<div id="myDiv">
  <p>This is some text.</p>
</div>

<button id="myButton">Slide</button>

jQuery:

$(document).ready(function(){
  $("#myButton").click(function(){
    $("#myDiv").slideToggle();
  });
});

In this example, the slideToggle() method is used to slide up or down the "myDiv" element when the "myButton" button is clicked.

References

Activity