In this tutorial, we will go over a very common but very effective interaction. Although CSS animations are great, The lack of total control over elements in CSS3 make it bothersome when incorporating interaction into your site. By using Javascript/JQuery and some logic, we can control our CSS3 animations to further improve our user experience.

Setup

First we will set up our HTML and CSS markup so we know what we are working with. As an example, we will have a circle transition across the page. Simple, but what if we want to stop the animation with a button and continue from the point we paused at. That is where JQuery (a Javascript Library) comes into play. JQuery will use events and logic to determine when to start/stop the animation, as well as know the exact coordinates to start from. Here is out markup we will be working with

As you can see, we created our circle, gave it some style, and added a translate class to our css which will be added/removed by our javascript. We reference the JQuery library so we can incorporate it into our project. The tricky part about starting a css transition after stopping is that it has a tendency to restart and play again. This will also be solved by Javascript.

The Javascript

Next, we will introduce some logic when adding our CSS classes through JQuery. take the JS code below and paste it between the <script> tags.

We have provided comments that walk you through step by step what is happening in the JQuery code provided. Let’s go through the function and see whats going on:

  1. Create a variable for JQuery to look for the .circle class
  2. Look for .button and when clicked, start a if/else statement to make decision
  3. Decision 1: if the button says ‘Play’, change button text to ‘Pause’ and add the class . translate
  4. Decision 2: If the button does not say ‘Play’, change the button text to ‘Play’, create a variable for calculating the margin-left value, remove the .translate class, and store the margin-left value to be used again.

Pretty nifty right? by simply adding and removing classes, we can mimic a start and pause effect. By letting the computer make decisions for us, it will allow us to switch out the letters in the button as well as save and resume the transition from the point in which we paused the animation.

Conclusion

Becoming an expert Front-end Designer takes a good understanding of what code is most efficient to incorporate and how to weave them all together. By letting CSS perform the animation and JQuery utilize logic to dictate the controls, we save ourselves from wasting time and headaches.