caveman/gatherer/assets/tag_images.js

83 lines
3.7 KiB
JavaScript

(function() {
var sectionEls = document.getElementsByTagName("section");
for(var i = 0; i < sectionEls.length; i++) {
var sectionEl = sectionEls[i];
(function(sectionEl) {
var images = sectionEl.getAttribute("data-images").split(" ").filter(function(image) { return !!image; });
if (images.length > 0) {
var imageContainer = document.createElement("div");
imageContainer.className = "images";
if (images.length == 1) {
/* Show a single image */
var img = document.createElement("p");
img.className = "image";
img.style.backgroundImage = "url('" + images[0] + "')";
imageContainer.appendChild(img);
} else {
/* Show slideshow */
/* url */
var currentImage = null;
/* <img> element */
var currentImg = null;
function show() {
var oldImage = currentImage;
var oldImg = currentImg;
var nextImage = null;
while(!currentImage || currentImage == oldImage) {
currentImage = images[Math.floor(images.length * Math.random())];
}
var retryTimeout;
let image = new Image();
image.src = currentImage;
image.onload = function() {
if (retryTimeout) {
clearTimeout(retryTimeout);
}
currentImg = document.createElement("p");
currentImg.className = "image";
currentImg.alt = "Preview image from dubious source";
currentImg.style.backgroundImage = "url('" + currentImage + "')";
currentImg.style.left = oldImg ? "100%" : "0";
imageContainer.appendChild(currentImg);
requestAnimationFrame(function() {
setTimeout(function() {
// slide
if (oldImg) {
oldImg.style.left = "-100%";
}
currentImg.style.left = "0";
setTimeout(function() {
if (oldImg) {
imageContainer.removeChild(oldImg);
}
// loop
show();
}, 5000 + Math.ceil(10000 * Math.random()));
}, 100);
});
};
retryTimeout = setTimeout(function() {
// img didn't load, cancel and retry
image.onload = null;
show();
}, 5000);
}
show()
}
sectionEl.style.backgroundPosition = "center";
sectionEl.style.backgroundSize = "cover";
sectionEl.className = "with-image";
var titleEl = sectionEl.getElementsByClassName("title")[0];
if (titleEl) {
titleEl.insertBefore(imageContainer, titleEl.firstChild);
}
}
})(sectionEl);
}
})()