Skip to content

Instantly share code, notes, and snippets.

@sisco70
Last active May 26, 2021 13:32
Show Gist options
  • Save sisco70/32771effdc740cfc251ac950c100d52f to your computer and use it in GitHub Desktop.
Save sisco70/32771effdc740cfc251ac950c100d52f to your computer and use it in GitHub Desktop.
While waiting for a slow file download, shows a spinner on the submit button.. Vanilla Javascript (Bootstrap not mandatory).
document.getElementById('submit_form').addEventListener('submit', async function (event) {
event.preventDefault();
let sub_btn = document.getElementById('submit_btn');
sub_btn.setAttribute('disabled', '');
let sub_btn_html = sub_btn.innerHTML;
sub_btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> ' + sub_btn_html;
try {
let response = await fetch(this.action, { method:'post', body: new FormData(this) });
if (response.ok) {
let [, filename] = response.headers.get('content-disposition').split('filename=');
let blob = await response.blob();
let downloadLink = document.createElement("a");
downloadLink.download = filename;
downloadLink.href = window.URL.createObjectURL(blob);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
else throw new Error("Network response was not OK.");
} catch (err) {
console.log('Fetch error: ' + err);
} finally {
sub_btn.removeAttribute('disabled');
sub_btn.innerHTML = sub_btn_html;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment