Showing and hiding elements.
In jQuery, you can show and hide elements using the .show()
and .hide()
methods, as well as the .toggle()
method for toggling visibility. Here are some basic examples:
1. .show()
Method
The .show()
method is used to display the hidden elements.
<!DOCTYPE html>
<html>
<head>
<title>Show Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button id="showButton">Show</button>
<div id="elementToShow" style="display:none;">This is a hidden element.</div>
<script>
$(document).ready(function(){
$("#showButton").click(function(){
$("#elementToShow").show();
});
});
</script>
</body>
</html>
2. .hide()
Method
The .hide()
method is used to hide the visible elements.
<!DOCTYPE html>
<html>
<head>
<title>Hide Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button id="hideButton">Hide</button>
<div id="elementToHide">This is a visible element.</div>
<script>
$(document).ready(function(){
$("#hideButton").click(function(){
$("#elementToHide").hide();
});
});
</script>
</body>
</html>
3. .toggle()
Method
The .toggle()
method is used to toggle between hiding and showing elements.
<!DOCTYPE html>
<html>
<head>
<title>Toggle Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button id="toggleButton">Toggle</button>
<div id="elementToToggle">This is an element to toggle.</div>
<script>
$(document).ready(function(){
$("#toggleButton").click(function(){
$("#elementToToggle").toggle();
});
});
</script>
</body>
</html>
Additional Options
You can also use optional parameters to add animations and set the duration of the show and hide actions.
- With duration:
$("#element").show(1000); // Shows the element over 1 second
$("#element").hide(1000); // Hides the element over 1 second
$("#element").toggle(1000); // Toggles the element's visibility over 1 second
- With callback function:
$("#element").show(1000, function() {
alert("Element is now visible.");
});
Using CSS Classes
Instead of using .show()
and .hide()
, you can also manipulate CSS classes to control visibility:
.hidden {
display: none;
}
<button id="toggleClassButton">Toggle Class</button>
<div id="elementToToggleClass" class="hidden">This is an element with a toggle class.</div>
<script>
$(document).ready(function(){
$("#toggleClassButton").click(function(){
$("#elementToToggleClass").toggleClass("hidden");
});
});
</script>
These methods and options provide you with a flexible way to show and hide elements in your web applications using jQuery.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.