refactor single.js a bit

This commit is contained in:
Rhiannon Morris 2020-08-03 19:38:14 +02:00
parent d2b2fdf2a5
commit c2a0ca6680

View file

@ -1,58 +1,60 @@
'use strict';
(function() { (function() {
'use strict';
function defined(x) {
return x !== null && typeof x !== 'undefined';
}
function getById(id) { return document.getElementById(id); } function getById(id) { return document.getElementById(id); }
function setImage(src, href, cw) { let mainfig = getById('mainfig');
let mainfig = getById('mainfig'); let mainimg = getById('mainimg');
let mainimg = getById('mainimg'); let mainlink = getById('mainlink');
let mainlink = getById('mainlink');
let caption = getById('cw');
if (defined(caption) && defined(cw)) { function openCW(caption, focusLink) {
caption.innerHTML = `<span id=cw-text>cw: <b>${cw}</b></span>`; mainfig.removeChild(caption);
} else if (defined(caption)) { mainlink.tabIndex = 0;
mainfig.removeChild(caption); if (focusLink) mainlink.focus();
} else if (defined(cw)) { }
let newCaption = document.createElement('figcaption');
newCaption.id = 'cw'; function addCWListeners(caption) {
newCaption.innerHTML = `<span id=cw-text>cw: <b>${cw}</b></span>`; if (caption) {
newCaption.onclick = openCW; caption.addEventListener('click', e => openCW(caption));
mainfig.insertBefore(newCaption, mainlink); caption.addEventListener('keyup',
e => { if (e.key == 'Enter') openCW(caption, true) });
}
}
function setImage(src, href, cw) {
let caption = getById('cw');
let cwText = `<span id=cw-text>cw: <b>${cw}</b></span>`;
if (cw && caption) {
caption.innerHTML = cwText;
} else if (caption) {
openCW(caption);
} else if (cw) {
let template = document.createElement('template');
template.innerHTML = `
<figcaption id=cw aria-role=button tabindex=0>
${cwText}
</figcaption>`;
let content = template.content;
addCWListeners(content.getElementById('cw'));
mainfig.insertBefore(content, mainlink);
mainlink.tabIndex = -1;
} }
mainimg.src = src; mainimg.src = src;
mainlink.href= href; mainlink.href = href;
} }
function activateButton(button) { function activateButton(button) {
setImage(button.value, button.dataset.link, button.dataset.warning); setImage(button.value, button.dataset.link, button.dataset.warning);
} }
function openCW() {
let mainfig = getById('mainfig');
let caption = getById('cw');
if (defined(caption)) {
mainfig.removeChild(caption);
}
}
function setup() { function setup() {
for (let button of document.querySelectorAll('#altlist input')) { for (let button of document.querySelectorAll('#alts input')) {
button.onchange = function(e) { button.onchange = e => { if (button.checked) activateButton(button); };
if (button.checked) activateButton(button);
};
} }
let caption = getById('cw'); addCWListeners(getById('cw'));
if (defined(caption)) {
caption.onclick = openCW;
}
} }
window.addEventListener('load', setup); window.addEventListener('load', setup);