-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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