CSS Animations in JavaScript & React

It's actually a webpage...

joyanna.dev/css-animations


There's a lot to cover! Feel free to use this webpage as a resource for all of the topics we'll be covering.


  1. Why do Animations Matter?
  2. What Animation Tools Do We Have?
  3. What are the Pros & Cons to using These Tools?
  4. How do Animations affect Performance & SEO
  5. How does The Browser Render Animations?
  6. Improving Accessibility
  7. Quick Tip: Themed Animations

✨ Why Animations Matter

Animation Drives User Engagement and Conversion

It grabs the User's Attention

  • "The human visual system is sensitive to motion..."
  • Which can be a good thing... or a bad thing
  • Subtle animations provide user feedback. It shows the user your app is actually "doing" something.
  • Either way! If you're using animations, studies show that your users are paying attention. Unless... you're using too much, and then they are annoyed.

References

The Role of Animation...
In UX, motion and animation can be helpful and communicative, if used with restraint. Motion is most often appropriate as a form of subtle feedback for microinteractions, rather than to induce delight or entertain users.
Page Laubheimer, Nielson Norman Group β€’ 2020

🐌 Let's talk about GOOD Animation Practices


  • Our brains are in-tune with the subtlety of animations.
  • UI elements should enhance an app.
  • Animations shouldn't get in the way of the functionality of the UI elements
  • Animations are different from Mobile to Web
  • The goal is to animate in a way that makes sense to our brains, by mimicing what we see in the real world.
  • Material Design has guidelines
  • No "Content Shifts", Negative for Usability
  • Use a Lazy Loader instead

References

The Ultimate Guide...
Material Design: Motion
So, if we sum up all of the above-mentioned rules and principles, the animation in the interface should reflect the movements that we know from the physical world β€” friction, acceleration, etc. Imitating the behavior of objects from the real world we can create a sequence that allows users to understand what to expect from the interface.
Taras Skytskyi β€’ UX Collective β€’ 2018

Back In MY Day...

We used JQuery And we LIKED it.


The way we create USED to create animations

  • Flash?
  • JQuery?
  • Dreamweaver? (you know to swap a photo on hover)

With the Release of CSS3 & HTML5 web changed a lot...

  • CSS3: 60FPS & GPU Rendering
  • JavaScript Animation Libraries
grandpa saying back in my day

πŸ›  Animation Tools

Here are a few tools and libraries that we use to animate web. (Sorry if your favorite isn't listed)


Design Programs: Smart Animations

Smart Animate makes it easy to quickly mock-up animations from screen to screen.


Transition between two states/frames in a component.

  • Figma: Smart Animate
  • Framer: Smart Components

Fast & Easy

  • Quick solution for prototyping and communicating an idea.
  • These don't necessarily export code, but there are plugins and other tools.

Communication

  • Creates clear concept of what kind of animations you would like the developer to create.
  • In some cases you can export code, but most likely will need to be looked at.

References

  1. Figma Animations
  2. Framer Animations
Figma Smart Animate Tool
Using Prototyping + Smart Animate

Figma creates the transition between screens

Lottie

Helps Designers be able to create complex animations. Exports JSON files for developers to use.


It's great for complex animations!

  • Can be exported from After Effects and other programs
  • Has plugin support for our favorite programs: Figma, Framer, Webflow, etc
  • Can Be Installed with an NPM package

References

  1. Lottie + Webflow
  2. Lottie + Figma
  3. Lottie Files

Framer + Framer-Motion


πŸ’ͺ Powerful Tools

Especially when using Libraries & Design-to-Dev plugins, we need to be careful of how often we use them.


Should be used sparingly!

  • Can Effect Performance & SEO
  • Not always supported in all browsers
  • Not always UX friendly

Right Tool for the Right Problem

In many cases these are exactly what you need!

  • Physics-based Motion
  • Interactive Graphic Elements
  • Intro Screens / Custom Animations

Why?

because Spiderman...

Holding back a train
Actual footage of the browser loading your animations...

πŸ™…πŸ»β€β™€οΈ A Bad Example


Rotating Circle Example

This shows two SVG circles that are rotated 360. One is exported using a plugin, the other is using CSS. For complex animations this plugin is perfect! In this case, we're asking the browser to use JavaScript to constantly re-render a transform.


The "Problem"

The problem here isn't that we're using javascript instead of CSS. The problem is that we're loading an entire library to rotate a circle. If all we want to do is rotate a complicated svg, we can do so without loading an entire animation library.



Don't do this:

circle rotates as javascript constantly changes the in-line style on an svg circle

When you can do this:

circle rotates as javascript constantly changes the in-line style on an svg circle

πŸ“ A Note on Performance

It's not really a matter of JavaScript vs CSS in some cases it's about the same from a performance standpoint. (for most modern browsers)


It's all in the Timing!

  • With how quickly web changes, it's important to take everything with a grain of salt.
  • Each application is different.
CSS transitions/animations are resampling element styles in the main UI thread before each repaint event happens, which is almost the same as resampling element styles via arequestAnimationFrame() callback, also triggered before the next repaint. If both animations are made in the main UI thread, there is no difference performance-wise.
MDN Web Docs, CSS & JavaScript Animation Performance β€’ 2022

Setting a transform with a 3D characteristic (like translate3d() or matrix3d()) triggers the browser to create a GPU layer for that element. So the GPU speed boost is not just for CSS animations – JavaScript animation can benefit too!
Jack Doyle β€’ CSS Tricks β€’ 2017

References

MDN Article
CSS Tricks Article

🍿 Buttery Smooth CSS Transitions


Understanding How the Browser Works: Critical Rendering Path

  • Styles > Layout > Paint > Composite
    1. Styles: calculates styles/fonts
    2. Layout: width/height; left/right/top/bottom;
    3. Paint: border-radius;box-shadow; color; background-color;
    4. Composite: transform:translate/scale/rotate; opacity;
  • Creating 60FPS by using properties that paint at the end of the process.
β€œ...avoid using transitions with the left/top/right/bottom properties. Those don’t create a fluid animation because they have the browser creating layouts each time, which will affect all of their children.”


References

Smooth As Butter Animations

Oooooooo!

This is what we want.

Smooth animations that load quickly.


aliens saying oooo ahhh
Users on your application...

πŸ’― Google, SEO & Lighthouse

We want all these to be good... Therefore we need to pay attention to our performance.

Bad UX affects Rankings

Many factors can play into a site's SEO, it's good to stay up-to-date on what is being calculated.
  • Google penalizes you for poor performance.
  • Users on Mobile Devices with a slow network.
  • First Contentful Paint
  • HTML Structure & Quality
  • Check Lighthouse for your performance score and suggested modifications.
  • ☝️ Use Semantic HTML

References

Lighthouse
Core Web Vitals...
Lighthouse is an open-source, automated tool for improving the quality of web pages. You can run it against any web page, public or requiring authentication. It has audits for performance, accessibility, progressive web apps, SEO and more.
Tools for Web Developers β€’ 2021

πŸ€¦πŸ»β€β™€οΈ Wait... What's Semantic HTML?

Semantic HTML relates the structure of the content to the browser.

Visual Hierarchy is well... Visual πŸ‘€

  • Limited time for crawlers to gain benneficial content from your site
  • Text should be in a tag that relates that it is text.
  • Negative Scoring will Impact SEO
  • You can use plugins to test your accessibility. Axe Dev Tools is a good one.
  • You can test your semantic validation. (see link below)

References

MDN Docs: Semantics
Markup Validation Service
Axe DevTools

Example:


<div class="wrapper">
<div>Important Headline</div>
<div>Paragraph that explains our headline.</div>
</div> πŸ‘Ž
<section>
<h2>Important Headline</h2>
<p>Paragraph that explains our headline.</p>
</section> πŸ‘

Wait... NO DIVs?

man saying wait what?

What! No DIVs?

you can still use divs, but there are a few things to keep in mind.

When to use which thing?

  • Is the content semantically related? or is the content self contained.
  • When in doubt, decide if it's a content or a wrapper.

☝️ Take Aways

  • Use a tag that fits the content
  • Stop using so many DIVS!


References

Stop Using so MANY DIVs!
Semantics: Article/Section/Div
When approaching which markup to use, ask yourself, "What element(s) best describe/represent the data that I'm going to populate?" For example, is it a list of data?; ordered, unordered?; is it an article with sections and an aside of related information?; does it list out definitions?; is it a figure or image that needs a caption?; should it have a header and a footer in addition to the global site-wide header and footer?; etc.
MDN Web Docs β€’ 2021

✨ CSS Transitions & Animations

What are they?


Transitions

  • Change between one state and another
  • Using Ease or a Bezier Curve defines how the browser transitions between each state

Animations

  • Uses Keyframes
  • Using Ease or a Bezier Curve define animation

REFERENCES

CSS3 Generator
example showing a choppy animation and a smooth one that loads in sections

Basic Syntax


The browser transitions from one property to another

  • Common Transitions transition: all 3s ease-in-out;
  • Calling out a propertytransition: color .2s ease-in, transform .6s ease-in-out;
  • Can be combined with hover-states and pseudo elements

Animations use Keyframes to change properties

  • Using Keyframes @keyframes{from {color:pink} to {color:blue}}
  • Keyframe %0%{color: pink} 50%{color: purple} 100%{color:blue};
  • Using Keyframes@keyframes { from {color: pink} to {color: blue} }
  • Reference the animation on the element you want to apply it to.animation: rotation 2s ease-in-out
circle rotates as javascript constantly changes the in-line style on an svg circle

So that's cool and all... now what?


Let's look at Practical Applications


Examples

  • Vanilla Javascript: Toggle a Class!
  • React + Styled Components: Toggle State!
  • React + Accessibility: Update ARIA Tag!


All of these based on CSS Transitions

kid with thumbs up saying very cool

🍦 Utilizing Javascript + CSS Transitions


Classic Vanilla Javascript

This is the typical way of using CSS transitions with Javascript. With the introduction of JavaScript Frameworks. We are able to manage state inside our application.


  1. Query The DOM
  2. Grab all the elements
  3. Turn it into an array...
  4. Loop over it
  5. Add an Event Listener
  6. Swap out the Class

And VOILA! You've made changes to the DOM...

Toggle a Class or Data-Attribute

  • So now that we have classes, we can use Javascript to β€œtoggle” a CSS class on an HTML element. This will make the browser transition between each of the properties. .toggle(β€˜myClass’)
  • We can do this a variety of ways, a very easy one is to use Javascript to β€œlisten” to see if an HTML element has been clicked. That will trigger our function which will then add or remove the CSS class from our element.addEventListener(β€˜click’, myfunction);

button toggles light and dark
View Project

πŸ–Ό Utilizing React + CSS Transitions

Instead of querying the DOM for our elements, we can update elements when there is a state change.

This example is using Styled Components / Emotion

  • You can use theuseState to toggle a menu open and closed.
  • First set up the initial state and the function...
    const [isOpen, setIsOpen] = useState(true);
  • Then pass the prop to the styles, or use them directly in the file.
    transform: translateX( $ {(props) => (props.isOpen ? '-100%' : '0%')} );
menu opens when clicked and classes change out
You can see the pre-generated classes swap out to open the menu.

This is fine... 🀨

Let's make it even better!

  • What if I told you we can make this better?
  • ...And more Accessible!
man saying better

🏷 Accessibility: ARIA Tags


What are ARIA tags?

Accessible Rich Internet Applications (ARIA) is a set of attributes that define ways to make web content and web applications (especially those developed with JavaScript) more accessible to people with disabilities.
MDN Web Docs β€’ 2022

What are some good places to use ARIA Tags?

  • Drop-downs
  • Accordions
  • Buttons
  • Forms
  • Tool-Tips

References

Aria Tags
React: Accessibility

πŸ’ͺ ARIA + React


The way we do thing!

  • Similarily we can use useState to set up our state.
  • Then we can toggle aria-hidden and aria-expanded with our state.
  • Using these attributes makes it easy for someone using a screen reader.
  • Additionally you can use id and aria-labelledby to closely pair the button and content
  • It's not required to use aria-labelledby, but it helps to create a structure that screen readers can pick up on. Similar to labels and inputs.

References

Accessible Accordions
WAI-ARIA Authoring Practices 1.2
example of an accordion opening and closing
View Project

It's a lot!

It's super useful for users.

It impacts Lighthouse scoring and the ability to easily navigate a page with a screen reader.


One Last Example! Using CSS Animations

  • Animations + SVGs
dog blinking with mouth open

SVG Animation Examples


This example is using SVGs and CSS classes.

  • Each class contains an animation
  • You can add those classes to different SVG elements and groups

How this Example was built

  1. Create a vector in your fav design program
  2. Copy as SVG
  3. Paste into your fav SVG Optimizer (SVGOMG)
  4. Copy and Paste the code into a browser-based code editing platform.
  5. Write some fun CSS Animations. 🀩
There is a lot going on in this particular example. Tons of absolute positioned items and pseudo elements. The point here was to show a few svgs animating. ☝️ It's not necessarily the most performant example.

References

SVGOMG
Codepen
CodeSandbox
animations with SVGs example
View Project

Themed Animations

One way to utlized Styled Components and Animated SVGs is to save your animations to your theme file.

Importing Themed Animations

  • You can import small utility animations into your SVGS
  • By doing this you don't have to load all of your animations in your global style sheet.
  • That way you only load animations when they are present on the page.
theme file with animations in it
Amimation Classes in Theme
importing from the theme to the SVG component
Example of bringing animation classes into the svg
SVG moves up and down
Animation Result...

Conclusion: The Manifesto!


Let's make GOOD Animations

  • Keeping in mind that PERFORMANCE changes our SEO scores!
  • Using ARIA tags to make a better user experience
  • If we use libraries or plugins, let's make sure it's justified.
  • Animations add to our UX, let's be mindful of how we use them.


THANK YOUUUUUU! πŸ™


I'm currently working at Regal Cinemas

psst... we're hiring for front-end developers!


Questions?