On gists
ResizeObserver.html
•
JavaScript
ResizeObserver.html
Raw
#
<!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>
<style>
.container {
display: flex;
width: 100%; /* This can be changed via the buttons. */
height: 200px;
padding: 8px;
background: #eaeaea;
}
/* Image Wrappers */
.container > div {
height: 200px;
min-width: 100px;
max-width: 200px;
flex: 1;
background-size: cover;
background-repeat: no-repeat;
}
/* The rest is just setup. */
#app {
display: flex;
flex-direction: column;
align-items: center;
font-family: sans-serif;
padding: 16px;
}
p {
margin-top: 32px;
text-align: center;
color: #4c11f7;
text-transform: uppercase;
font-weight: 600;
font-size: 14px;
letter-spacing: 0.5px;
}
.change-size {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
}
</style>
</head>
<body>
<div id="app">
<div class="container"></div>
<p>Container Size</p>
<div class="change-size">
<button value="100%">100%</button>
<button value="1400px">1400px</button>
<button value="640px">640px</button>
<button value="200px">200px</button>
</div>
</div>
<script>
/* Attach ResizeObserver to the container. */
const resizeObserver = new ResizeObserver(onResize);
resizeObserver.observe(document.querySelector('.container'));
const IMAGE_MAX_WIDTH = 200;
const IMAGE_MIN_WIDTH = 100;
function onResize(entries) {
const entry = entries[0];
const container = entry.target;
/* Calculate how many images can fit in the container. */
const imagesNeeded = Math.ceil(entry.contentRect.width / IMAGE_MAX_WIDTH);
let images = container.children;
console.log(images);
/* Remove images as needed. */
while (images.length > imagesNeeded) {
images[images.length - 1].remove();
}
/* Add images as needed. */
while (images.length < imagesNeeded) {
let seed = Math.random().toString().replace('.', '');
const newImage = document.createElement('div');
const imageUrl = `https://picsum.photos/seed/${seed}/${IMAGE_MAX_WIDTH}`;
newImage.style.backgroundImage = `url(${imageUrl})`;
container.append(newImage);
}
}
/* The rest is for the container size buttons. */
function changeSize(e) {
if (!e.target.value) return;
const container = document.querySelector('.container');
container.style.width = e.target.value;
}
const changeSizeButtons = document.querySelector('.change-size');
changeSizeButtons.addEventListener('click', changeSize);
</script>
</body>
</html>