TalentJR

Lesson 16

Simple Animations

Animate elements with JS and CSS

1What is Animation in JavaScript?✨

Animation in JavaScript allows you to create dynamic and engaging user experiences on web pages. By combining JavaScript with CSS, you can make elements move, change size, and transition smoothly.

2Why Learn Animations?🎯

  • ✓ Captivating user interactions
  • ✓ Enhance visual storytelling
  • ✓ Improve user engagement
  • ✓ Make your web projects stand out

3CSS Transitions💡

CSS transitions allow you to change property values smoothly over a given duration. To animate an element, you need to define a starting state and a final state.

4Example:🚀

💻 code
const box = document.querySelector('.box');
box.addEventListener('click', () => {
  box.style.transition = 'all 0.5s';
  box.style.transform = 'translateX(100px)';
});

In this code, when you click the box, it moves 100 pixels to the right over half a second.

5Using requestAnimationFrame🔍

For more control over animations, use the `requestAnimationFrame` method. This method allows you to create smooth animations that synchronize with the display refresh rate.

6Example:⭐

💻 code
let position = 0;
function animate() {
  position += 2;
  box.style.transform = `translateX(${position}px)`;
  if (position < 400) {
    requestAnimationFrame(animate);
  }
}
animate();

This example continuously moves the box to the right until it reaches 400 pixels.

7Combining CSS and JavaScript🧩

You can combine CSS animations with JavaScript to create more complex effects. For instance, you can trigger CSS keyframe animations using JavaScript events.

8Example:🎈

💻 code
const animatedBox = document.querySelector('.animated-box');
animatedBox.addEventListener('mouseover', () => {
  animatedBox.classList.add('bounce');
});
animatedBox.addEventListener('mouseout', () => {
  animatedBox.classList.remove('bounce');
});

In this example, when you hover over the box, it bounces using a CSS animation defined in your stylesheet.

9Your Animation Project✨

Now it's time to put everything together! Create an interactive animation project that incorporates CSS transitions, `requestAnimationFrame`, and event listeners. Think about an idea that excites you—maybe a bouncing ball or a moving character!

This is your chance to showcase what you've learned and create something truly fun!

🎯 Practice Challenges

Master Simple Animations by completing all 3 difficulty levels

🟢 EASY

Simple Animations - Easy Challenge

Start with the basics. Perfect for beginners!

🟡 MEDIUM

Simple Animations - Medium Challenge

Get more challenging. Build your confidence!

🔴 HARD

Simple Animations - Hard Challenge

Master this concept. Prove your skills!

🏆 Study a lesson for 2+ minutes to earn +10 TalentJR Points a day. Badges, certificates & prizes →

Ready to Master Simple Animations? 🚀

Complete the challenges, take the quiz and keep your learning streak going!