diff options
author | Martin Fischer <martin@push-f.com> | 2025-03-14 07:10:37 +0100 |
---|---|---|
committer | Martin Fischer <martin@push-f.com> | 2025-03-14 08:35:51 +0100 |
commit | 8e0e3165807c5123148ba1b205854a723e3fc5c2 (patch) | |
tree | bb6e6935e0f6b84505b97d9089bc30cac38fa797 | |
parent | 1f860bc34f01d25f95310ea8cb7e2f27fff3283b (diff) |
refactor: build DOM via JS
-rw-r--r-- | index.html | 6 | ||||
-rw-r--r-- | script.js | 36 |
2 files changed, 25 insertions, 17 deletions
@@ -3,11 +3,9 @@ <title>Share a geographic position</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" /> <body> - <h1 id="heading"></h1> - <div id="instructions" hidden>Open in</div> - <ul id="links"></ul> - <script src="script.js"></script> + <div id="content"></div> <noscript>This website requires JavaScript</noscript> + <script src="script.js"></script> <style> body { max-width: 40ch; @@ -17,33 +17,32 @@ const LINKS = [ }, ]; -const heading = document.getElementById('heading'); +const content = document.getElementById('content'); route(); // TODO: route on hashChange function route() { const latLon = parseLatLon(location.hash.slice(1)); + content.innerHTML = ''; if (!latLon) { - heading.textContent = 'not yet implemented'; + document.title = 'Share a location'; + content.append(createEl('h1', {}, ['not yet implemented'])); } else { - const linkList = document.getElementById('links'); - document.getElementById('instructions').hidden = false; - document.title = 'Open location'; - heading.textContent = ''; + content.append(createEl('p', {}, ['Open in'])); + + const linkList = createEl('ul'); const [lat, lon] = latLon; - for (const link of LINKS) { - const li = document.createElement('li'); - const a = document.createElement('a'); - a.href = link.url.replace('{lat}', lat).replace('{lon}', lon); - a.textContent = link.label; - li.appendChild(a); - linkList.appendChild(li); + for (const linkSpec of LINKS) { + const url = linkSpec.url.replace('{lat}', lat).replace('{lon}', lon); + const link = createEl('a', { href: url }, [linkSpec.label]); + linkList.append(createEl('li', {}, [link])); } + content.append(linkList); } } @@ -63,3 +62,14 @@ function parseLatLon(text) { } return [lat, lon]; } + +function createEl(tag, attrs = {}, content = []) { + const el = document.createElement(tag); + for (const [name, value] of Object.entries(attrs)) { + el.setAttribute(name, value); + } + for (const child of content) { + el.append(child); + } + return el; +} |