Skip to content

Instantly share code, notes, and snippets.

@tomshaw
Created March 3, 2020 17:56
Show Gist options
  • Save tomshaw/d0bc129de40b07b5f6c34e5ec70e38dc to your computer and use it in GitHub Desktop.
Save tomshaw/d0bc129de40b07b5f6c34e5ec70e38dc to your computer and use it in GitHub Desktop.
Vanilla javascript download progress.
// ==========================================================================
// ReleaseDownload Progress Bar
// ==========================================================================
import AbstractObject from './AbstractObject';
export default class ReleaseDownload extends AbstractObject {
constructor(el, options) {
super(el, options);
this.el = el;
this.options = options;
this.createChildren();
this.initHandlers();
this.enableListeners();
}
createChildren() {
this.$button = document.getElementById('download');
this.$progress = document.getElementById('progressbar');
this.$progressPercent = document.getElementById('progressPercent');
this.$progressComplete = document.getElementById('progressComplete');
}
initHandlers() {
this.handleButtonClick = this.onButtonClick.bind(this);
}
enableListeners() {
this.$button.addEventListener('click', this.handleButtonClick);
}
onButtonClick(e) {
e.preventDefault();
let url = e.target.getAttribute('data-url');
let file = e.target.getAttribute('data-file');
let request = new XMLHttpRequest();
request.addEventListener('readystatechange', (e) => {
if (request.readyState == 2 && request.status == 200) {
// Download is being started
} else if (request.readyState == 3) {
// Download is under progress
} else if (request.readyState == 4) {
this.$progressComplete.innerHTML = 'Complete!';
let anchor = document.getElementById('save-file');
anchor.download = file;
anchor.href = window.URL.createObjectURL(request.response);
anchor.click();
}
});
request.addEventListener('progress', event => {
let percent = (event.loaded / event.total) * 100;
this.$progress.style.width = `${percent}%`;
this.$progressPercent.innerHTML = `${Math.round(percent).toFixed(0)}%`;
this.$progress.setAttribute("aria-valuenow", percent);
});
request.responseType = 'blob';
request.open('get', url);
request.send();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment