Skip to content

Instantly share code, notes, and snippets.

@SteveHere
Forked from adactio/formProgress.js
Last active December 29, 2020 14:28
Show Gist options
  • Save SteveHere/a3fe292a56a1a90d692dfb00220d9100 to your computer and use it in GitHub Desktop.
Save SteveHere/a3fe292a56a1a90d692dfb00220d9100 to your computer and use it in GitHub Desktop.
Show a progress bar with every form that has a method of POST. Particularly nice if there's a file upload involved.
// Licensed under a CC0 1.0 Universal (CC0 1.0) Public Domain Dedication: http://creativecommons.org/publicdomain/zero/1.0/
((win, doc)=>{ 'use strict';
[...doc.querySelectorAll('form[method="post"]')].forEach((formElement)=>{
function ajax (elem) {
let progressBar = Object.assign(doc.createElement('progress'), {max:100, value:0});
formElement.appendChild(progressBar);
let url = elem.action, xhr = new XMLHttpRequest();
xhr.open(elem.method, url, true);
xhr.onload=(ev)=>{ win.location = url; };
xhr.upload.onprogress=(ev)=>{ if (ev.lengthComputable) { progressBar.value = (ev.loaded / ev.total) * 100; } };
xhr.send(new FormData(elem));
}
formElement.addEventListener('submit', (ev)=>{ ajax(this); ev.preventDefault(); }, false);
});
})(this, this.document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment