view Transition

by jpeter06

HTML

<button id="button">Add image</button>
<button id="buttonT">Change last image viewTransition</button>
<div id="container">

</div>

CSS

@keyframes fade-in {
  from { opacity: 0; }
}

@keyframes fade-out {
  to { opacity: 0; }
}

@keyframes slide-from-right {
  from { transform: translateX(30px); }
}

@keyframes slide-to-left {
  to { transform: translateX(-30px); }
}

#container {
  position:absolute;
  top:100px;
  width:200px;
  height:200px;
  background:green;
}
::view-transition-old() {
  animation: 890ms cubic-bezier(0.4, 0, 1, 1) both fade-out,
    1800ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-left;
}

::view-transition-new() {
  animation: 810ms cubic-bezier(0, 0, 0.2, 1) 90ms both fade-in,
    1800ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-right;
}

JavaScript

const button = document.getElementById('button');
const buttonT = document.getElementById('buttonT');
const container = document.getElementById('container');

button.addEventListener("click", addImage);
buttonT.addEventListener("click", addImageT);

function addImage() {
	const newImage = document.createElement("img");
   newImage.style.height = '100px';
    newImage.style.width = '100px';
	newImage.src = "https://source.unsplash.com/random";
		container.appendChild(newImage);
}


function addImageT() {
	var lastChild = container.lastElementChild;
	const newImage = document.createElement("img");
   newImage.style.height = '100px';
    newImage.style.width = '100px';
	newImage.src = "https://source.unsplash.com/random";
	document.startViewTransition(() => { // This kicks off the view transition
  	lastChild.remove();
		container.appendChild(newImage);
	});
}