Skip to content

Instantly share code, notes, and snippets.

@sttt
Created February 7, 2018 02:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sttt/7740bd213f1618bb8479ce9b8220af18 to your computer and use it in GitHub Desktop.
Save sttt/7740bd213f1618bb8479ce9b8220af18 to your computer and use it in GitHub Desktop.
Animate Flexbox Order
<h1>Hover to reorder</h1>
<div class="group">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
</div>
var group = document.querySelector(".group");
var nodes = document.querySelectorAll(".box");
var total = nodes.length;
var ease = Power1.easeInOut;
var boxes = [];
for (var i = 0; i < total; i++) {
var node = nodes[i];
// Initialize transforms on node
TweenLite.set(node, { x: 0 });
boxes[i] = {
transform: node._gsTransform,
x: node.offsetLeft,
y: node.offsetTop,
node
};
}
group.addEventListener("mouseenter", layout);
group.addEventListener("mouseleave", layout);
function layout() {
group.classList.toggle("reorder");
for (var i = 0; i < total; i++) {
var box = boxes[i];
var lastX = box.x;
var lastY = box.y;
box.x = box.node.offsetLeft;
box.y = box.node.offsetTop;
// Continue if box hasn't moved
if (lastX === box.x && lastY === box.y) continue;
// Reversed delta values taking into account current transforms
var x = box.transform.x + lastX - box.x;
var y = box.transform.y + lastY - box.y;
// Tween to 0 to remove the transforms
TweenLite.fromTo(box.node, 0.5, { x, y }, { x: 0, y: 0, ease });
}
}
<script src="//cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/TweenMax.min.js"></script>
body {
color: #333;
padding: 10px 24px;
}
h1 {
font-weight: normal;
font-size: 24px;
}
.group {
width: 600px;
height: 150px;
padding: 4px;
background: #ddd;
display: flex;
flex-direction: row;
}
.box {
margin: 4px;
padding: 8px;
font-size: 18px;
flex: 1;
align-self: stretch;
&:nth-child(1) {
background: rgba(63, 81, 181, 0.6);
}
&:nth-child(2) {
background: rgba(103, 58, 183, 0.6);
}
&:nth-child(3) {
background: rgba(33, 150, 243, 0.6);
}
&:nth-child(4) {
background: rgba(0, 188, 212, 0.6);
}
}
.group.reorder {
.box:nth-child(1) {
order: 2;
}
.box:nth-child(2) {
order: 4;
}
.box:nth-child(3) {
order: 1;
}
.box:nth-child(4) {
order: 3;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment