What does this jQuery snippet demonstrate?
This jQuery snippet demonstrates how to toggle the visibility of an HTML element with a smooth sliding animation using jQuery and CSS — without shifting other elements on the page.
When a user clicks on an element with the class .demo-header
, the script does the following:
- Finds the next sibling element with the class
.demo-content
. - Toggles its visibility using a sliding animation (
slideToggle("slow")
), creating a smooth open/close effect. - Toggles a CSS class (
.demo-header-close
) on the clicked header, allowing you to visually indicate whether the content is open or closed (e.g., by changing an arrow icon or background color).
This technique keeps the layout stable, meaning it doesn’t push surrounding elements up or down abruptly — it simply slides the target element open or closed within its own space.
Demo
HTML
<div class="demo-wrap">
<div id="demo-header" class="demo-header">
What does the word “mare” in 'nightmare' mean?
</div>
<div id="demo-content" class="demo-content">
<div class="demo-text">
The word “mare” refers to a female goblin that sits on you, suffocates you while you sleep, entangles her hair around you, and tries to induce bad thoughts.
</div>
</div>
<div class="demo-content-sub">
<p><i class="fa-solid fa-person-circle-question fa-4x"></i></p>
<p>click on the header to show or hide the answer</p>
</div>
</div>
CSS
.demo-container {
position: relative;
margin: 0 auto;
max-width: 500px;
min-height: 240px;
}
.demo-content {
display: none;
background-color: rgba(255, 255, 255, 0.92);
position: absolute;
padding: 16px 0;
border-bottom-right-radius: 6px;
border-bottom-left-radius: 6px;
z-index: 1;
}
.demo-text {
padding: 1em;
}
.demo-content-sub {
padding: 0.5em 1em;
text-align: center;
border: 1px solid rgba(255, 255, 255, 0.65);
border-bottom-right-radius: 6px;
border-bottom-left-radius: 6px;
}
.demo-header {
position: relative;
padding: 10px 20px;
background-color: #525252;
color: #FFFFFF;
border-top-right-radius: 6px;
border-top-left-radius: 6px;
cursor: pointer;
}
.demo-header::after {
position: absolute;
content: "\f0ab";
font-family: FontAwesome;
font-size: 16px;
color: #F0F0F0;
right: 6px;
}
.demo-header-close::after {
position: absolute;
content: "\f0aa";
font-family: FontAwesome;
font-size: 16px;
color: #CCCCCC;
right: 6px;
}
JS
$(document).ready(function() {
$("#demo-header").click(function() {
$(this).next("#demo-content").slideToggle("slow");
$(this).toggleClass("demo-header-close");
});
});
Alternate table row styles
Conditional formatting of table rows
Copy text to clipboard
Disable space input in text fields
Multi step form with progress indicator
Read more or less
Remove the leading and trailing space
Short functions
Toggle visibility with a slide effect
Toggle visibility without pushing content down
Validate checkboxes
Validate input fields
Validate radio buttons
Validate TinyMce editor