Skip to content

Instantly share code, notes, and snippets.

@ryandejaegher
Last active February 10, 2022 12:07
Show Gist options
  • Select an option

  • Save ryandejaegher/3f2d0993f1fe5680e8e6cc4e6981a356 to your computer and use it in GitHub Desktop.

Select an option

Save ryandejaegher/3f2d0993f1fe5680e8e6cc4e6981a356 to your computer and use it in GitHub Desktop.
Randomize Image Order #javascript #squarespace
{
"scripts": [],
"styles": []
}
<!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>Document</title>
</head>
<body>
<div class="grid">
<img src="https://source.unsplash.com/random?skateboard" />
<img src="https://source.unsplash.com/random?skateboard-1" />
<img src="https://source.unsplash.com/random?skateboard-3" />
<img src="https://source.unsplash.com/random?skateboard-4" />
<img src="https://source.unsplash.com/random?skateboard-5" />
<img src="https://source.unsplash.com/random?skateboard-6" />
<img src="https://source.unsplash.com/random?skateboard-7" />
<img src="https://source.unsplash.com/random?skateboard-8" />
<img src="https://source.unsplash.com/random?skateboard-9" />
<img src="https://source.unsplash.com/random?skateboard-10" />
</div>
</body>
</html>
/*
Shuffle children of a parent element. Useful for randomizing an image gallery.
@param {String} selector The selector to match against
*/
var shuffleChildren = function (selector) {
var parent = document.querySelector(selector);
try {
for (var i = parent.children.length; i >= 0; i--) {
parent.appendChild(parent.children[(Math.random() * i) | 0]);
}
} catch (e) {
console.error(e);
}
};
shuffleChildren('.grid');
*,
*:before,
*:after {
box-sizing: border-box;
}
html,
body {
height: 100%;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans',
'Helvetica Neue', sans-serif;
}
.flex {
display: flex;
}
.flex-col {
flex-direction: column;
}
.grid {
height: 100%;
width: 100%;
display: grid;
grid-template-columns: repeat(3, 1fr);
}
img {
width: 100%;
height: 100%;
max-width: 100%;
object-fit: cover;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment