jQuery Hide/Show
The hide()
and show()
methods in jQuery are used to toggle the visibility of HTML elements. These methods are simple yet powerful, allowing you to create dynamic and interactive web pages with ease.
Using hide()
The hide()
method hides the selected elements by setting their CSS display
property to none
.
$("#element").hide();
Explanation: This code hides the element with the ID element
. The element will no longer be visible but remains in the DOM.
Using show()
The show()
method makes hidden elements visible by resetting their display
property.
$("#element").show();
Explanation: This code makes the element with the ID element
visible. It restores the element’s original display property.
Example: Toggle Visibility
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Hide/Show Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<p id="text">This is a paragraph.</p>
<button id="hideButton">Hide Text</button>
<button id="showButton" style="display:none;">Show Text</button>
<script>
$(document).ready(function() {
$("#hideButton").click(function() {
$("#text").hide();
$("#hideButton").hide();
$("#showButton").show();
});
$("#showButton").click(function() {
$("#text").show();
$("#hideButton").show();
$("#showButton").hide();
});
});
</script>
</body>
</html>
Explanation: In this example, the hide()
and show()
methods toggle the visibility of a paragraph. Clicking "Hide Text" hides the paragraph and the button, while "Show Text" restores both.
Key Takeaways
- Visibility Control: Use
hide()
andshow()
to dynamically control the visibility of elements. - Non-Removal: These methods only hide or display elements; they do not remove them from the DOM.
- Chaining: Combine
hide()
andshow()
with other jQuery methods for enhanced functionality.