Recipe 17.3

Animating DOM Transitions

This page shows an example of using the View Transitions API to provide a cross-fade animation between two DOM states. A CSS rule is applied to slow the effect down so it can be more easily seen.

Click “View Profile” to show the profile with an animated transition.

Demo

Phillip Chavez

CEO

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc in porta justo. Duis bibendum iaculis auctor. Vestibulum ut elit in lacus congue vehicula. Aliquam laoreet varius ipsum sit amet iaculis. Cras fringilla mattis lacinia. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Sed blandit varius pharetra.

Code

JavaScript
const navigation = document.querySelector('#form');
const navigationButton = document.querySelector('#form button');
const profile = document.querySelector('#profile');

navigationButton.addEventListener('click', () => {
  document.startViewTransition(() => {
    profile.classList.remove('d-none');
    navigation.classList.add('d-none');
  });
});
HTML
<style>
  ::view-transition-old(root),
  ::view-transition-new(root) {
    animation-duration: 2s;
  }

  #container {
    height: 20em;
  }
</style>

<div id="container">
  <div id="form">
    <button class="btn btn-primary">View Profile</button>
  </div>

  <div id="profile" class="d-none">
    <h2>Phillip Chavez</h2>
    <h3>CEO</h3>
    <img src="https://randomuser.me/api/portraits/men/40.jpg">
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc in porta justo. Duis bibendum iaculis auctor.
      Vestibulum ut elit in lacus congue vehicula. Aliquam laoreet varius ipsum sit amet iaculis. Cras fringilla mattis
      lacinia. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Sed blandit varius
      pharetra.
    </p>
  </div>
</div>
Web API Cookbook
Joe Attardi