Skip to content

Instantly share code, notes, and snippets.

@Thomasparsley
Last active May 17, 2022 19:51
Show Gist options
  • Save Thomasparsley/b818e59a6733c40116816cf78f406e96 to your computer and use it in GitHub Desktop.
Save Thomasparsley/b818e59a6733c40116816cf78f406e96 to your computer and use it in GitHub Desktop.
HTMX - Reorder list anim
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTMX animating re-ordering</title>
<script src="https://unpkg.com/htmx.org@1.7.0"
crossorigin="anonymous"></script>
<script>
htmx.config.useTemplateFragments = true;
</script>
<script>
var tmp = []
htmx.on("htmx:beforeSwap", (event) => {
let swaps = event.target.querySelectorAll("[hx-anim-swap]");
// for each swap, save into tmp the current position of the element and id of the element
swaps.forEach((swap) => {
tmp.push({
id: swap.id,
position: swap.getBoundingClientRect()
});
});
})
htmx.on("htmx:afterSwap", (event) => {
tmp.forEach((swap) => {
const element = document.querySelector(`#${swap.id}`);
if (!element) {
return;
}
const oldTop = swap.position.top;
const newTop = element.getBoundingClientRect().top;
// if the element is still in the DOM, move it to the position it was in before the swap
element.animate([
{ transform: `translateY(${oldTop - newTop}px)` },
{ transform: `translateY(0px)` },
], { duration: 500, easing: "ease-in-out" });
});
tmp = [];
})
</script>
<style>
button {
width: 300px;
height: 50px;
}
</style>
</head>
<body>
<ul id="list">
</ul>
<button id="swap" hx-get="./x-1.html" hx-target="#list">
Swap
</button>
</body>
</html>
<button hx-swap-oob="outerHTML:#swap" id="swap" hx-get="./x-2.html" hx-target="#list">
Swap
</button>
<li hx-anim-swap id="a">A</li>
<li hx-anim-swap id="b">B</li>
<li hx-anim-swap id="c">C</li>
<li hx-anim-swap id="d">D</li>
<button hx-swap-oob="outerHTML:#swap" id="swap" hx-get="./x-3.html" hx-target="#list">
Swap
</button>
<li hx-anim-swap id="d">D</li>
<li hx-anim-swap id="c">C</li>
<li hx-anim-swap id="x">X</li>
<li hx-anim-swap id="b">B</li>
<li hx-anim-swap id="a">A</li>
<button hx-swap-oob="outerHTML:#swap" id="swap" hx-get="./x-1.html" hx-target="#list">
Swap
</button>
<li hx-anim-swap id="c">C</li>
<li hx-anim-swap id="d">D</li>
<li hx-anim-swap id="x">X</li>
<li hx-anim-swap id="a">A</li>
<li hx-anim-swap id="b">B</li>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment