Nash Vail Nash Vail - 4 months ago 12
Javascript Question

CSS animation help. Plays only one way

So I am trying to build an ios 7 like switch for my web app . I am 60% done. I have applied an animation code which stretches the knob while it moves to and fro. But the problem is the stretching affect appears only while turning the switch off. See it yourself here iOS 7 style switch

The markup uses a checkbox that's hidden by making its opacity 0 .

Markup:

<input type = "checkbox" name= "toggle" id="toggle">
<label for= "toggle"></label>


CSS Animation code:

@-webkit-keyframes strSqu {
0% { width : 27px; }
50% { width : 30px ;}
100% { width : 27px; }
}


Applied to:

input#toggle:checked + label:before {
margin-left: 20.8px;
border :1px solid rgba(201, 201, 201, 0.21);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
-webkit-animation-name : strSqu;
-webkit-animation-duration : 400;
}


I am still a rookie when it comes to dealing with pseudo elements. Am I missing something ?

Answer

The issue here is that you can't apply the same transition twice to an element or it will just be ignored the second time. That's why the solution proposed by @JoshuaCarmody doesn't work. Instead if you define a second identical animation like so:

@-webkit-keyframes strSqu2 {
   0% { width : 27px; }
   50% { width : 60px ;}
   100% { width : 27px; }
}

And apply that to the unchecked state:

input#toggle + label:before{
    content : " ";
    display : block;
    background-color : #fff;
    border :1px solid #4dc15e;

    height : 27px;
    width : 27px;
    border-radius: 15px;
    transition : all 400 cubic-bezier(.6,-0.22,.18,1.02) ;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.21);
    -webkit-animation-name : strSqu2;
    -webkit-animation-duration : 400;
}

It will work. This seems counter-intuitive to me especially in your case where the animation starts and ends the same way, but it does work.