function UploadQueue(options) { this.queue = options.queue_element; this.previews = options.preview_area; this.submit = options.submit_button; this.addEvents(); } UploadQueue.prototype.addEvents = function() { var that = this; that.queue.addEventListener('change', function() { that.showSpinner(that.queue); that.clearPreviews(); for (var i = 0; i < that.queue.files.length; i++) { var callback = (i !== that.queue.files.length - 1) ? null : function() { that.hideSpinner(); }; that.addPreviewForFile(that.queue.files[i], i, callback); }; }); that.submit.addEventListener('click', function(e) { e.preventDefault(); that.process(); }); }; UploadQueue.prototype.clearPreviews = function() { this.previews.innerHTML = ''; } UploadQueue.prototype.addPreviewForFile = function(file, index, callback) { if (!file) { return false; } var preview = document.createElement('img'); preview.id = 'upload_preview_' + index; preview.style.maxHeight = '150px'; var reader = new FileReader(); var that = this; var appendMe = function() { preview.src = reader.result; if (callback) { preview.addEventListener('load', function() { callback(); }); } that.previews.appendChild(preview); }; var waitForMe = function() { var previews = that.previews.childNodes; if (previews.length === 0 || previews[previews.length - 1].id === 'upload_preview_' + (index - 1)) { appendMe(); } else { setTimeout(waitForMe, 10); } }; reader.addEventListener('load', waitForMe, false); reader.readAsDataURL(file); }; UploadQueue.prototype.process = function() { this.showSpinner(this.submit); alert('Should now upload ' + this.queue.files.length + " files"); }; UploadQueue.prototype.showSpinner = function(sibling) { if (this.spinner) { return; } this.spinner = document.createElement('div'); this.spinner.className = 'spinner'; sibling.parentNode.appendChild(this.spinner); }; UploadQueue.prototype.hideSpinner = function() { this.spinner.parentNode.removeChild(this.spinner); this.spinner = null; };