Skip to content

Instantly share code, notes, and snippets.

@hideya
Last active April 25, 2023 05:49
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hideya/16ed168a42f74eb5d2162b4e743940ff to your computer and use it in GitHub Desktop.
Save hideya/16ed168a42f74eb5d2162b4e743940ff to your computer and use it in GitHub Desktop.
CSS Flex Wrap Animation (code assumes no change in items except xy coords): https://codepen.io/hideya/pen/Jamabx
window.addEventListener('load', function(event) {
var targetClassName = 'flex-wrap-anim';
var defaultDuration = '0.3s';
var dummyList = [];
function addDummy(item, duration) {
var top = item.offsetTop;
var left = item.offsetLeft;
setTimeout(function() {
item.style.position = 'absolute';
item.style.top = top + 'px';
item.style.left = left + 'px';
var dummyDiv = document.createElement('div');
dummyDiv.classList.add(targetClassName + '-dummy');
var rect = item.getBoundingClientRect();
dummyDiv.style.width = rect.width + 'px';
dummyDiv.style.height = rect.height + 'px';
dummyDiv.style.visibility = 'hidden';
dummyDiv['__' + targetClassName + '_pair'] = item;
dummyDiv['__' + targetClassName + '_duration'] = duration;
item.parentNode.appendChild(dummyDiv);
dummyList.push(dummyDiv);
}, 0);
}
var conts = document.getElementsByClassName(targetClassName);
for (var i = 0, max = conts.length; i < max; i++) {
var cont = conts[i];
cont.style.position = 'relative';
var duration = cont.getAttribute('data-duration')
|| defaultDuration;
var items = cont.getElementsByTagName('div');
for (var i = 0, max = items.length; i < max; i++) {
addDummy(items[i], duration);
}
}
window.addEventListener('resize', function(event) {
dummyList.forEach(function(dummyDiv) {
var item = dummyDiv['__' + targetClassName + '_pair'];
var duration = dummyDiv['__' + targetClassName + '_duration'];
if (item.offsetTop != dummyDiv.offsetTop) {
item.style.transition = 'all ' + duration;
item.style.top = dummyDiv.offsetTop + 'px';
item.style.left = dummyDiv.offsetLeft + 'px';
} else {
item.style.transition = '';
item.style.left = dummyDiv.offsetLeft + 'px';
}
});
});
});
@felubra
Copy link

felubra commented Jan 8, 2020

Hi,
There is a typo in the line 30: "positoin"
However, this works like a charm, thanks for sharing!

@hideya
Copy link
Author

hideya commented Jan 10, 2020

Hi @felubra, thanks for pointing out the typo! I've fixed it, as well as the one at codepen.
Much appreciated!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment