Reputation: 135
I have a simple toggle to open up a slide panel on my site. I used CSS to animate the slide and all works nicely, but how can I add animation to the panel when someone closes the panel? So slide in and out with animation.
jQuery
$(".toggle-slide-panel").click(function(){
$(".slide-panel").toggle();
});
CSS
.slide-panel{
background-color: #cccccc;
width: 350px;
height: 100%;
position: fixed;
z-index: 9;
top: 0;
left: 0;
display: none;
animation: slide-panel 300ms;
}
@keyframes slide-panel{
from{
margin-left: -350px;
opacity: 0;
}
to{
margin-left: 0;
opacity: 1;
}
}
Upvotes: 0
Views: 1603
Reputation: 1466
As the others say as well, i would highly recommend you not to use keyframes as the support is relatively poor (see edit below).
Instead you could just toggle a class with the respective CSS and a transition
$(".toggle-slide-panel").click(function(){
$(".slide-panel").toggleClass("active");
});
And CSS:
.slide-panel{
transform: translate3d(-350px,0,0);
transition: 0.3s ease-in-out;
}
.active {
transform: translate3d(0,0,0);
}
You can try it out in this fiddle which is an update of the one you provided.
EDIT: With regard to support I might have been a tad too fast - according to caniuse.com the support for @keyframes and transition is quite similar:
http://caniuse.com/#search=keyframes
http://caniuse.com/#feat=css-transitions
Personally, however, I would still prefer transition over @keyframes, but that might just be because I'm not used to working with keyframes.
Edit 2:
If you are concerned about support for older versions, here's just a few notes:
translate3d
with a regular left
property (i.e. left: -350px;
before toggle and left: 0;
on the .active
class). To make this hardware accelerated you could add a transform: translateZ(0);
to the .slide-panel
class which also activates it. transform: translate(-350px,0)
which has better support than translate3d
while animating smoother than left:
. Upvotes: 1
Reputation: 376
I would recommend you not to use CSS keyframes and instead rely on jQuery for the animation.
All you have to do is to add jQuery UI and use the following JS code:
$(".toggle-slide-panel").click(function(){
$(".slide-panel").toggle('slide', {direction: 'left'});
});
Take a look at this jsFiddle: https://jsfiddle.net/NikolaosG/adwj6bfo/1/ for the specific example.
Upvotes: 0
Reputation: 227
Checkout this link you just might have to add an alternate css for the animation. Something like this
animation-direction: alternate; /* or: normal */
https://css-tricks.com/snippets/css/keyframe-animation-syntax/ Hope it helps :).
Upvotes: 0