view-transition-demo

by Richard Hunter

HTML

<div id="container"><div class="alpha"></div></div>
<button id="button">change square</button>

CSS

.alpha {
  height: 200px;
  background: hotpink;
}
.alpha, .beta {
  view-transition-name: foo;
}

.beta {
  height: 200px;
  background: dodgerblue;
}

button {
  margin: 10px;
}

body {
  margin: 0;
}

@keyframes leave {
  from { transform: translate(-100vw, 0); }
  to { transform: translate(0, 0); }
}

@keyframes enter {
  from { transform: translate(0, 0); }
  to { transform: translate(100vw, 0); }
}

::view-transition-old(foo) {
  animation: 0.5s linear both enter;
}

::view-transition-new(foo) {
  animation: 0.5s linear both leave;
}

JavaScript

let square = 'alpha';

function changeSquare() {
	container.querySelector('.' + square).remove();
	square = square === 'alpha' ? 'beta' : 'alpha';
  const newSquare = document.createElement('div');
  newSquare.className = square;
  container.appendChild(newSquare);
}

function onClick() {
	//changeSquare();
	const transition = document.startViewTransition(() => changeSquare());
}

button.addEventListener('click', onClick);