Reputation: 9855
I have a section on my website that when a user clicks I would like it to expand, I'm using the jQuery's toggleClass
for this...
expandable: function(e) {
e.preventDefault();
$(this).closest('article').toggleClass('expanded', 1000);
}
This is working fine, only I'd like to somehow animate it. In chrome my article slowly grows to the new size, only in Firefox it 'instantly' resizes itself with no animation, is there a way to have this animate?
Upvotes: 43
Views: 146619
Reputation: 91
I attempted to use the toggleClass method to hide an item on my site (using visibility:hidden as opposed to display:none) with a slight animation, but for some reason the animation would not work (possibly due to an older version of jQuery UI).
The class was removed and added correctly, but the duration I added did not seem to make any difference - the item was simply added or removed with no effect.
So to resolve this I used a second class in my toggle method and applied a CSS transition instead:
The CSS:
.hidden{
visibility:hidden;
opacity: 0;
-moz-transition: opacity 1s, visibility 1.3s;
-webkit-transition: opacity 1s, visibility 1.3s;
-o-transition: opacity 1s, visibility 1.3s;
transition: opacity 1s, visibility 1.3s;
}
.shown{
visibility:visible;
opacity: 1;
-moz-transition: opacity 1s, visibility 1.3s;
-webkit-transition: opacity 1s, visibility 1.3s;
-o-transition: opacity 1s, visibility 1.3s;
transition: opacity 1s, visibility 1.3s;
}
The JS:
function showOrHide() {
$('#element').toggleClass("hidden shown");
}
Thanks @tomas.satinsky for the awesome (and super simple) answer on this post.
Upvotes: 8
Reputation: 87073
.toggleClass()
will not animate, you should go for slideToggle()
or .animate()
method.
Upvotes: 26
Reputation: 1185
You can simply use CSS transitions, see this fiddle
.on {
color:#fff;
transition:all 1s;
}
.off{
color:#000;
transition:all 1s;
}
Upvotes: 20
Reputation: 7086
You should look at the toggle
function found on jQuery. This will allow you to specify an easing method to define how the toggle works.
slideToggle
will only slide up and down, not left/right if that's what you are looking for.
If you need the class to be toggled as well you can deifine that in the toggle
function with a:
$(this).closest('article').toggle('slow', function() {
$(this).toggleClass('expanded');
});
Upvotes: 6
Reputation: 150293
jQuery UI extends the jQuery native toggleClass
to take a second optional parameter: duration
toggleClass( class, [duration] )
Upvotes: 67
Reputation: 9855
Should have checked, Once I included the jQuery UI Library it worked fine and was animating...
Upvotes: 0