Javascript

More Advanced jQuery Showing and Hiding

More Advanced jQuery Showing and Hiding

These techniques help you:

  • Chain animations

  • Use custom speeds and easing

  • Add callbacks (run code after animation finishes)

  • Create accordion-style, conditional, or multi-state UI behaviors


1️⃣ Chaining Multiple Effects

js
$('#btn').click(function () {
$('#box')
.slideUp(400)
.delay(300)
.fadeIn(500);
});

What it does:

  • Slides up

  • Waits 300ms

  • Fades in


2️⃣ Using Callbacks (After Animation Ends)

js
$('#btn').click(function () {
$('#box').fadeOut(400, function () {
alert('Animation complete!');
});
});

Useful for triggering something after the show/hide finishes.


3️⃣ Conditional Show/Hide Based on State

js
$('#btn').click(function () {
if ($('#box').is(':visible')) {
$('#box').slideUp();
} else {
$('#box').slideDown();
}
});

This gives you full control instead of just toggling.


4️⃣ Accordion-Style Behavior

Hide all sections and only show the one clicked:

html
<div class="accordion">
<h3>Section 1</h3>
<div class="panel">Content 1</div>
<h3>Section 2</h3>
<div class="panel">Content 2</div>
</div>
js
$('.panel').hide(); // Hide all initially

$('.accordion h3').click(function () {
$(this).next('.panel').slideToggle()
.siblings('.panel').slideUp();
});


5️⃣ Using Easing for Smooth Feel

js
$('#box').fadeToggle(600, 'swing'); // default easing
$('#box').fadeToggle(600, 'linear'); // linear easing

Requires jQuery UI for additional easing options like easeInOutBounce.


6️⃣ Custom Duration and Animation

js
$('#box').animate({
width: 'toggle',
height: 'toggle',
opacity: 'toggle'
}, 700);

You can animate multiple properties at once — more than just show/hide!


Example: Tab-Like Interface

html
<button class="tab" data-target="#tab1">Tab 1</button>
<button class="tab" data-target="#tab2">Tab 2</button>

<div id="tab1" class="content">Content for Tab 1</div>
<div id="tab2" class="content">Content for Tab 2</div>

js
$('.content').hide(); // Hide all initially

$('.tab').click(function () {
const target = $(this).data('target');
$('.content').slideUp();
$(target).slideDown();
});


✅ Summary Table

Technique Description
.slideUp() / .slideDown() Vertical animation
.fadeIn() / .fadeOut() Fade animation
.animate({...}) Custom animation of CSS values
callback functions Run code after animation finishes
chaining Run multiple animations in sequence

Leave a Reply

Your email address will not be published. Required fields are marked *