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,29 +1,44 @@
'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>`;
} else if (defined(caption)) {
mainfig.removeChild(caption); mainfig.removeChild(caption);
} else if (defined(cw)) { mainlink.tabIndex = 0;
let newCaption = document.createElement('figcaption'); if (focusLink) mainlink.focus();
newCaption.id = 'cw'; }
newCaption.innerHTML = `<span id=cw-text>cw: <b>${cw}</b></span>`;
newCaption.onclick = openCW; function addCWListeners(caption) {
mainfig.insertBefore(newCaption, mainlink); if (caption) {
caption.addEventListener('click', e => openCW(caption));
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;
@ -34,25 +49,12 @@ 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);