Skip to content

Instantly share code, notes, and snippets.

@lmiller1990
Created April 15, 2021 15:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lmiller1990/7a60a87f2c70381e8f11b8655153e859 to your computer and use it in GitHub Desktop.
Save lmiller1990/7a60a87f2c70381e8f11b8655153e859 to your computer and use it in GitHub Desktop.
Vanilla FLIP Sundae
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="m-4">
<button class="bg-gray-300 my-2 px-4 py-2 rounded-md" onclick="flip()">Flip</button>
<div class="my-1 relative max-w-sm bg-green-400 w-full h-12 rounded-md flex items-center">
<div id="box" class="left bg-red-200 h-10 px-2 absolute rounded-md flex items-center">BOX</div>
</div>
<script src="./index.js"></script>
<style>
.left { left: 5px; }
.right { right: 5px; }
<style>
</body>
</html>
function flip() {
const elm = document.querySelector('#box')
// First: get the current bounds
const first = elm.getBoundingClientRect()
// execute the script that causes layout change
elm.classList.toggle('left')
elm.classList.toggle('right')
// Last: get the final bounds
const last = elm.getBoundingClientRect()
// Invert: determine the delta between the
// first and last bounds to invert the element
const deltaX = first.left - last.left
const deltaY = first.top - last.top
const deltaW = first.width / last.width
const deltaH = first.height / last.height
requestAnimationFrame(() =>
console.log('Calling requestAnimationFrame'))
console.log('Animating')
// Play: animate the final element from its first bounds
// to its last bounds (which is no transform)
elm.animate([{
transformOrigin: 'top left',
transform: `
translate(${deltaX}px, ${deltaY}px)
scale(${deltaW}, ${deltaH})
`
}, {
transformOrigin: 'top left',
transform: 'none'
}], {
duration: 300,
easing: 'ease-in-out',
fill: 'both'
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment