Exploring Animation Techniques with JavaScript and CSS

·

7 min read

Animations have become an attractive way to engage users on websites. So while I was learning about animations, I tried creating simple animations using JavaScript and CSS separately. And, it turns out there are some good differences between the two ways of doing it. As a fellow learner, I thought I'd share what I figured out.

CSS Animations: Making Things Look Cool😎

With CSS animations, we're making our website look cooler. It’ll use those neat effects, like things sliding smoothly or fading in. CSS uses two amazing things "transitions" and “keyframes” to make changes happen over time.
It's like setting the speed and number of times something happens.

Now, let me show you how a transition looks with a simple example like below:

<button class="hover-button">Hover Me</button>
/* Button Style */ 
.hover-button {
  padding: 10px 20px;
  background-color: #3498db; /* Blue background */
  color: white; /* White text */
  border: none;
  cursor: pointer;

  /* Transitions */
  transition: background-color 0.3s ease, color 0.3s ease, transform 0.5s ease;
}

/* Hover Effect */
.hover-button:hover {
  background-color: orange; /* Turns to orange background */
  color: red; /* Text turns red */
  font-style: italic; /* Text becomes italic */
  transform: perspective(800px) rotateY(180deg); /* Flips like a card */
}

The result of how the button changes as we hover over it:

So, here we used three transitions to make the button change when we hover over it.

  • Background Color Transition:
transition: background-color 0.3s ease;

This transition makes the button's background color change when you hover. It turns from blue to orange.. It takes 0.3 seconds (0.3s) to complete and uses an easing function.

  • Text Color Transition:
transition: color 0.3s ease;

This transition makes the text-color change when you hover over. It turns text color changes from white to red. It also takes 0.3 seconds (0.3s) to complete.

  • Transform Transition:
transition: transform 0.5s ease;

This transition applies to the transform property. The transform property in CSS is like a special tool that lets you change how things look and move on your website.
The line perspective(800px) rotateY(180deg); does two things:

  • perspective(800px): gives an element a 3D-like look, like you're seeing it from a distance.

  • rotateY(180deg): this makes the element flip around like that. The 180deg means a half-flip.

Now, let's talk about my favorite one keyframes. Keyframes let you control the animation's every detail – from where an element starts, how it evolves, to where it ends up. By picking different points during an animation, you create a sequence of changes.

Understanding Keyframes with an Example:

I am going to take a set of images, and I want to make them appear and disappear in a certain pattern. Here's how we do it:

Firstly, We’ll have to set up the images - let’ say I’ll use some Shinchan images. After placing the images within a container using html and css by adjusting them accordingly for the webpage.
And to understand the context better this is the result I am expecting,

(pardon my video editing skills 🥲)

Now, let’s see the use of keyframes to bring the images into action.

@keyframes headTurn {
  0% {
    opacity: 0; 
    transform: scale(0.8); 
  }
  25%, 50%, 75% {
    opacity: 1;
    transform: scale(1); 
  }
  100% {
    opacity: 0; 
    transform: scale(0.8); 
  }
}

Let’s break it down:

So, headTurn is the name given to the animation sequence defined by @keyframes. It is like a nickname or we can say a tag we use to control our animation.

  • At the start (0%) and end (100%) of the animation, the image i.e. our element starts and ends with low opacity and a slightly smaller size (transform: scale(0.8)). This is the reason for the fade-in and fade-out effect combined with a gentle size change.

  • At the middle stages 25%, 50%, 75%, the element becomes fully visible and returns to its original size (transform: scale(1)). This is when a particular image takes on the main role in the animation.

Then we apply the headTurn animation we created to our images:

.animation-image {
max-height: 100%;
position: absolute;
opacity: 0;
animation: headTurn 9s infinite;
}

The .animation-image class contains our images. We start with them being invisible by setting opacity to 0. Then, we use the headTurn script to make them appear and vanish. This keeps repeating for 9 seconds in a loop, creating an engaging animation effect.

So, for each image we can also have a set of timings defined:

.animation-image:nth-child(1) {
animation-delay: 0s;
}
.animation-image:nth-child(2) {
animation-delay: 3s;
}
.animation-image:nth-child(3) {
animation-delay: 6s;
}
  • The first image, targeted by .animation-image:nth-child(1), starts immediately with no delay (0s).

  • The second image, targeted by .animation-image:nth-child(2), starts after a 3-second delay.

  • The third image, targeted by .animation-image:nth-child(3), starts after a 6-second delay.

(nth-child is a way to pick out a specific image in the group of images by its position)


Animating with JavaScript: Adding Interaction and Control🎛️

Now that we've explored CSS animations, let's see animation using JavaScript. JavaScript brings interactivity, allowing animations to respond to user actions in realtime.

For JavaScript animations, the most commonly used technique is manipulating CSS properties using JavaScript. The best thing I like about animation with JS is it is engaging, fun and used to get better interactivity on websites.

Let’s see how we can use JavaScript functions to make the animations interactive with a simple example.
Observe the below result that I am expecting and how it changes the action of animation according to the mouse click:

Let's see how we can achieve something like that,
As usual, first we have to set up our HTML structure. Choosing the images and addressing them with ID’s and creating styles in css as we want to.

Then, if you have more images it’s always better to store in arrays. As I am using more than 3 images I would like to use Javascript arrays. By setting up my array object as images it’ll be easy to swap the images during animations.

I’ll be using 2 arrays for the animation like this,

const images = {
    shinchanEating: 'shinchan-eating.jpg',
    shinchanLeft: 'shinchan-head-left.jpg',
    shinchanRight: 'shinchan-head-right.jpg',
    sheroHungry: 'shero-hungry.jpg',
    himaAngry: 'hima-angry.jpg'
};
const eatingImages = [
    'shinchan-eating.jpg',
    'shero-eating.jpg',
    'hima-eating.jpg'
];

Using functions for managing these array’s functionality will be very helpful for making transitions between images also helps us understand quickly.
So, I am using a function called updateImages

Let’s see the code snippet and see how we can use it,

// The function updates images based on given sources
function updateImages(shinchanSrc, sheroSrc, himaSrc) {
shinchan.src = shinchanSrc;
shero.src = sheroSrc;
hima.src = himaSrc;
}

Here comes the main part and heart of our animation 😉
So, to trigger these animations, we need an event listener that responds to user actions. In our case, I want every click on Shinchan to result in change in the animation. Let's add this interactive touch:

// an event listener to Shinchan
shinchan.addEventListener('click', () => {
});

With each click, the animation logic within the event listener activates, taking us to different phases. Let’s see it’s action during different animation phases:

1. Shinchan Joyful Eating Phase:

// Transition to eating animation
updateImages(images.shinchanEating, 'transparent.png', 'transparent.png');

In this phase, updateImages switches Shinchan's image to him eating, while keeping Shero and Hima hidden.

2. Here comes Shero’s hungry face Phase:

// Transition to left turn animation
updateImages(images.shinchanLeft, images.sheroHungry, 'transparent.png');

Now, updateImages presents Shinchan with his head turned left, and Shero becomes hungry.

3. Oh no now himawari’s angry face Phase:

// Transition to right turn animation
updateImages(images.shinchanRight, 'transparent.png', images.himaAngry);

With this call, Shinchan turns to the right, and watches Hima staring with an angry expression.

4. All three Eating Together in peace Phase:

// Transition to eating together animation
updateImages(eatingImages[0], eatingImages[1], eatingImages[2]);

In the final phase, Shinchan get’s an idea and all three characters join in the feast together.

So like these, adding the event listener makes the animation more interactive. Users can control the story by clicking on any element. Each click leads to different parts of the animation, smoothly changing images with the help of the updateImages function.

Not only this we can use a lot of JavaScript functions.

As a fan of Event listener function here are some I discovered that can often be used to improve interactivity with animations on our web pages:

  1. click: When you click, something happens.

  2. mouseenter / mouseleave: Move over, action starts; move away, it stops.

  3. mousedown / mouseup: Click and hold, watch the action; release, see the change.

  4. mousemove: As you move your mouse, things follow.

  5. keydown / keyup: Press keys, animations begin; release, they end.

  6. scroll: Scroll down, things come alive.

  7. submit: Form filled, animation kicks in.

  8. load: Page or image loads, animation begins.

  9. resize: Change window size, animations adapt.

  10. focus / blur: Click on or leave, watch animations react.

Woah imagine the combination of CSS and JavaScript actions - it really blows my mind already thinking what kind of super cool things we can make with these🤯
But hey, to know all that amazing things, I guess I need to learn a lot 😶‍🌫️.
So, let’s keep exploring, wandering, learning 🤓


Bye 👋😄