The Yo-Yo wheel Effect using HTML, CSS & JS
Here is the end result I wanted to achieve.
- Clicking the start button will start the animation.
- The wheel starts to rotate/spin on itself and at the same time translate horizontally.
- Arriving at the right, the animation ends and the wheel rolls back to its original point.
- Then it starts again, and goes on like this until the stop button is hit.
For the html code, we require only a container which will contain our wheel image and a button to start/stop the animation.
The button behaves as a push down button. This is achieved by having a box-shadow property on the button with only the vertical shadow set. And, on the pseudo-class active of the button, the shadow is removed and the button is translated down to have the push down effect. Here are the code to achieve this.
Next, the styling of the wheel and its container is very important, so that the wheel does not roll outside of its container. In this example, the wheel is set to a width of 100 pixels and the width of its container is set to 600 pixels. Hence, we can only move it to the right by a maximum of 600 – 100 = 500 pixels. As for rotating the wheel, the greater degree chosen, the wheel will appear to be moving faster.
Next step, we need to toggle the animate class on the wheel to make it move back and forth. What’s happening here is that, when the start button is clicked, the animate-wheel class is added to the wheel. But arriving on the right, it would stay there.
Then, I had to find a solution to make it roll back to the starting position. That’s when I decided to use an interval timer. The transition takes 6 seconds as specified by the CSS. Then, after each 5 seconds interval I toggle the animate-wheel class. When the class is removed, the wheel animation ends and it moves back to the starting point. Then the timer starts the animation again, thus we are able to make it move continuously.
Finally, I was able to put together several pieces of learning acquired during the past few weeks and come up with this simple animation using:
- Some basic html tags
- CSS properties, pseudo-class, transform and animations