I'm trying to use jQuery's slideToggle function to show or hide a panel which has been hidden using CSS position, rather than display:none (as this causes issues with a Google Map in one of my panels).
At the moment I'm just hiding and showing the panels like so, but some animation would be nice:
$('.panel').addClass('hidden');
$('.head > span').addClass('closed');
$('.head').click(function() {
$(this).next('.panel').toggleClass('hidden');
$(this).children('span').toggleClass('open');
});
Any ideas?
jQuery slideToggle () method is used to hide or display the selected DOM elements with a sliding effect. In other words, slideToggle () method toggles between slideUp () and slideDown () methods. If the DOM element is hidden, slideDown () method is run to slide it down to display it.
The slideToggle () Method in jQuery is used to show the hidden elements or hide the visible elements respectively i.e. it toggles between the slideUp () and slideDown () methods. slideDown () is run when the element is hidden. slideUp () is run when the element is visible.
The slideToggle () method toggles between slideUp () and slideDown () for the selected elements. This method checks the selected elements for visibility. slideDown () is run if an element is hidden. slideUp () is run if an element is visible - This creates a toggle effect. Optional. Specifies the speed of the slide effect.
Let’s see how complicated it is to pull off a function like slideToggle with plain JavaScript. Before doing anything, I looked up the web and found some interesting solutions. But none was as smooth as jQuery’s slideUp, slideDown, and slideToggle.
slideToggle animates height of the element in question apart from visibility. Not sure how exactly you have used CSS position to show/hide your panels. Based on that you have to build you own animation using animate function. Another quick way could be to
For showing element:
Hide the element (using jquery hide())
Apply your class to show element (i.e. to adjust its position)
Now apply slideDown
For hiding content:
Apply slideUp - use callback function to do steps 2 & 3
Apply your class to hide element (i.e. to adjust its position outside window)
Show the element (using jquery show())
Edit: Illustrative code goes below (assuming that 'hidden' classes will do CSS positioning to hide the element):
function customSlideToggle(e)
{
var show = e.hasClass('hidden');
if (show) {
e.hide();
e.removeClass('hidden')
e.slideDown('slow');
}
else
{
e.slideUp('slow', function() {
e.addclass('hidden');
e.show();
});
}
}
slideToggle()
is an alternative to toggle()
, which shows/hides the selected items depending on its current visible state.
You needn't worry about the classes at all if you are simply trying to get the animation to work.
So, just try the following to see what you get:
$(this).next('.panel').slideToggle();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With