Demo: onloaded

Quick demo for using `onloaded` with a container-type selector. Vanilla JS / no libraries.

by Luke Edwards

HTML

<script src="https://unpkg.com/onloaded@1.0.0/dist/onloaded.min.js"></script>
<button id="add">Add Images</button>
<button id="reset">Reset All</button>

<ul id="logs"></ul>

<div style="position:relative">
	<hr>
	<div id="progress"></div>
	<div id="container"></div>
</div>

CSS

body {
	padding: 0;
	margin: 0;
}

button {
	padding: 8px 16px;
	margin: 16px 8px;;
	-webkit-appearance: none;
	background: none;
	border: 2px solid green;
	display: inline-block;
	font-size: 16px;
	cursor: pointer;
}

#reset {
	border-color: red;
}

#logs {
	height: 120px;
	margin: 10px;
	border: 1px solid #d0d0d0;
	overflow-y: auto;
	list-style-image: square;
	padding-left: 25px;
}

#logs li {
	line-height: 25px;
}

li.success { color:green }
li.error { color:red }

#progress {
	height: 3px;
	background: #6cc644;
	position: absolute;
	left: 0;
	top: 0;
}

#container {
	padding: 0 10px 10px;
}

#container > img {
	display: block;
	float: left;
	margin: 0 5px 5px 0;
	min-width: 100px;
	background: grey;
	height: 110px;
}

Babel + JSX

const $ = str => document.querySelector(str);

const logs = $('#logs');
const box = $('#container');
const bar = $('#progress');

const NUM = 12; // num to add

// DEMO
$('#add').onclick = ev => {
	ev.preventDefault();
	var images = Array(NUM).fill().map(addImage);
	
	// attach listeners!
	onloaded(images, {
		onProgress: setProgress,
		onLoad(img) {
			log(`Loaded: ${img.src}`, 'success');
		},
		onError(img) {
			log(`Failed: ${img.src}`, 'error');
		},
		onComplete(val, stats) {
			setProgress(val); // 100%
			log(`Finished!`);
			for (let k in stats) {
				log(`--> ${stats[k]} ${k}`);
			}
		}
	});
};

$('#reset').onclick = ev => {
  ev.preventDefault();
	empty(box);
	empty(logs);
	setProgress(0);
}


// BEGIN HELPERS

function setProgress(val) {
	bar.style.width = val * 100 + '%'; 
}

function log(msg, type) {
  const li = document.createElement('li');
  li.innerText = msg;
	li.className = type;
  logs.appendChild(li);
	logs.scrollTop = logs.scrollHeight;
}

function addImage() {
  const img = document.createElement('img');
  const risk = Math.ceil(Math.random() * 1000); // 10% error
	
	if (risk < 100) {
		img.src = `//foobar-${risk}.jpg`
	} else {
		const size = Math.random() * 3 + 1;
		let width = Math.random() * 110 + 100;
	  width = Math.round(width * size);
		const height = Math.round(140 * size);
		img.src = `//lorempixel.com/${width}/${height}/?${risk}`;
	}
	
  box.appendChild(img);
	
	return img;
}

function empty(el) {
  var kids=el.children, len=kids.length;
	while (len--) el.removeChild(kids[len]);
}