quidipo/js/image_viewer.js

118 lines
3.2 KiB
JavaScript

function pop(event) {
var target = event.target.parentNode;
if (target.nodeName != "FIGURE") {
target = event.target;
}
var href = target.parentNode.dataset.href;
var alt = target.firstElementChild.alt;
var viewer = document.getElementById('viewer');
var image = document.createElement('img');
image.src = href;
image.alt = alt;
image.id = 'img' + target.parentNode.parentNode.id;
viewer.appendChild(image);
viewer.classList.remove('hidden');
}
function unpop(event) {
var viewer = document.getElementById('viewer');
viewer.classList.add('hidden');
if (viewer.lastChild.nodeName == 'IMG') {
viewer.removeChild(viewer.lastChild);
}
}
function display(event) {
if (event.button != 1) {
return;
}
var target = event.target.parentNode;
if (target.nodeName != "FIGURE") {
target = event.target;
}
var href = target.parentNode.dataset.href;
window.open(href, '_blank');
}
function displayNeighbour(which) {
var viewer = document.getElementById('viewer');
var current = viewer.lastChild;
if (current.nodeName != 'IMG') {
return;
}
var ref_image_container = document.getElementById(current.id.slice(3))
var new_image_container = which == 'next' ?
ref_image_container.nextElementSibling :
ref_image_container.previousElementSibling;
if (new_image_container == null) {
return;
}
var new_image = new_image_container.firstElementChild;
current.src = new_image.dataset.href;
current.alt = new_image_container.firstElementChild.firstElementChild.firstElementChild.alt;
current.id = 'img' + new_image_container.id;
}
function displayPrev(event) {
displayNeighbour('prev');
}
function displayNext(event) {
displayNeighbour('next');
}
/* Adds new HTML elements for interactive viewing */
var viewer = document.createElement('div');
viewer.id = 'viewer';
viewer.classList.add('hidden');
var close = document.createElement('div');
close.id = 'close';
close.classList.add('viewer_button');
close.addEventListener('click', unpop);
viewer.appendChild(close);
/* not implemented yet */
var prev = document.createElement('div');
prev.id = 'prev';
prev.classList.add('viewer_button');
prev.addEventListener('click', displayPrev);
viewer.appendChild(prev);
var next = document.createElement('div');
next.id = 'next';
next.classList.add('viewer_button');
next.addEventListener('click', displayNext);
viewer.appendChild(next);
/* not implemented yet */
document.body.appendChild(viewer);
document.body.addEventListener(
'keydown',
(event) => {
if (event.defaultPrevented) {
return;
}
switch (event.key) {
case "Escape":
unpop();
break;
case "ArrowLeft":
displayPrev();
break;
case "ArrowRight":
displayNext();
break;
}
}
);
/* Makes thumbnails interactive */
for (var thumb of document.getElementsByClassName('thumbnail')) {
thumb.dataset.href = thumb.href;
thumb.removeAttribute('href');
thumb.style = "cursor: pointer;";
thumb.addEventListener('click', pop);
thumb.addEventListener('auxclick', display);
}