From 5636edd5b6af3486284b430f660b1b9e309a3671 Mon Sep 17 00:00:00 2001 From: Carson Fleming Date: Fri, 20 Oct 2023 23:37:28 -0400 Subject: Bring it all together and nitpick the appearance --- static/js/ajax.js | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 static/js/ajax.js (limited to 'static/js/ajax.js') diff --git a/static/js/ajax.js b/static/js/ajax.js new file mode 100644 index 0000000..e31a009 --- /dev/null +++ b/static/js/ajax.js @@ -0,0 +1,47 @@ +(function () { + const btn = document.querySelector('#shortenButton'); + const inpUrl = document.querySelector('#url'); + const inpSlug = document.querySelector('#slug'); + + function shorten (e) { + if (!inpUrl.value) return; + + const req = new XMLHttpRequest(); + req.addEventListener('load', () => { + const reply = JSON.parse(req.responseText); + if (req.status != 201) { + btn.innerText = reply.uiString || 'API Error'; + btn.classList.add('error'); + console.error(req.status, reply.errorMessage); + return; + } + + inpUrl.value = reply.data.shortUrl; + inpSlug.value = ''; + btn.removeEventListener('click', shorten); + btn.classList.remove('error'); + btn.innerText = 'Copy'; + btn.addEventListener('click', copyUrl); + inpUrl.focus(); + inpUrl.select(); + }); + req.addEventListener('error', () => { + btn.innerText = 'Connection Error'; + btn.classList.add('error'); + }) + + if (inpSlug.value) + req.open('PUT', '/'+encodeURIComponent(inpSlug.value)); + else + req.open('POST', '/'); + req.setRequestHeader('Content-Type', 'application/json'); + req.send(JSON.stringify({url: encodeURI(inpUrl.value)})); + } + + async function copyUrl(e) { + await navigator.clipboard.writeText(encodeURI(inpUrl.value)); + btn.innerText = 'Copied!'; + } + + btn.addEventListener('click', shorten); +})(); \ No newline at end of file -- cgit v1.2.3