Examples
jQuery hide()
Demonstrates how to use the simple hide() method in jQuery to make elements invisible.
Another hide() Example
Shows how to hide specific parts of the text on a page using jQuery.
jQuery hide() and show()
Using jQuery, you can toggle the visibility of HTML elements with the hide() and show() methods.
Example:
The following code hides all <p> elements when the "Hide" button is clicked, and shows them again when the "Show" button is clicked:
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
These methods are useful for creating interactive content that responds to user actions.
Syntax
$(selector).hide(speed, callback);
$(selector).show(speed, callback);
The speed parameter is optional and controls how fast the element is hidden or shown. It can be:
- "slow"
- "fast"
- A value in milliseconds (e.g., 1000 for 1 second)
- The callback parameter is also optional. It allows you to specify a function that will run once the hide() or show() action is complete.
(You'll learn more about callback functions in a later chapter.)
Example: Using hide() with Speed
The following example hides all <p> elements over a duration of 1 second when a button is clicked:
$("button").click(function(){
$("p").hide(1000);
});
This creates a smooth hiding effect by specifying the speed in milliseconds.
jQuery toggle()
The toggle() method allows you to switch between hiding and showing elements.
If the element is visible, it will be hidden; if it’s hidden, it will be shown.
Example: Toggling Visibility
The following code toggles the visibility of all <p> elements when a button is clicked:
$("button").click(function(){
$("p").toggle();
});
Syntax
$(selector).toggle(speed, callback);
- speed (optional) – Specifies the speed of the toggle effect.Possible values: "slow", "fast", or a number in milliseconds (e.g., 1000).
- callback (optional) – A function to be executed after the toggle action is complete.
This method is useful for creating simple toggle effects without having to use both hide() and show() separately.