function createNewElement(tag){return document.createElement(tag)}
function findElementById(id){return document.getElementById(id)}
function findAllByTag(tag,parent){return (parent == undefined ? document : parent).getElementsByTagName(tag)}
// Useful for HtmlCollection, NodeList, String types
function iterate(array, callback, scope){for (var i=0,n=array.length; i< n; i++)callback.call(scope, array[i], i, array);} // passes back necessary data
// Callback processes data retrieved from the .target.result field in the parameter passed to it.
function loadFileObject(fileObj, loadedCallback){var reader = new FileReader();reader.onload = loadedCallback;reader.readAsDataURL(fileObj);}
window.addEventListener('load', onDocumentLoaded, false);
function onDocumentLoaded(evt)
{
findElementById('addBtn').addEventListener('click', onAddButtonClicked, false);
}
/* HTML below function needs to create - Skip img creation since it's generated when files are picked */
/*
<div class='item'>
<img height='100px' width='100px'/><br>
<input type='file'/>
</div>
*/
function onAddButtonClicked(evt)
{
var wrapper = createNewElement('div');
wrapper.className = 'item';
//var img = createNewElement('img');
//img.style.height = '100px';
//wrapper.appendChild(img);
var input = createNewElement('input')
input.type = 'file';
// Enable multiple selection for file inputs
// input.multiple = 'true';
input.addEventListener('change', onFileChanged, false);
input.name = 'inputFiles[]';// Include [] so PHP can retrieve all files
wrapper.appendChild(input);
findElementById('previewHolder').appendChild(wrapper);
}
function onFileChanged(evt)
{
var numFiles = this.files.length;
var itemWrapper = this.parentNode;
var fileInput = this;
if (numFiles === 0)
{
// No files chosen, remove preview/file-picker element
var previewHolder = itemWrapper.parentNode;
previewHolder.removeChild(itemWrapper);
}
else
{
// Remove existing images
while (findAllByTag('img', itemWrapper).length != 0)
itemWrapper.removeChild( findAllByTag('img', itemWrapper)[0] );
iterate(this.files, loadAndPreviewImage);
function loadAndPreviewImage(fileObj)
{
loadFileObject(fileObj, onFileObjLoaded);
function onFileObjLoaded(evt)// Retrieve data using evt.target.result
{
var img = createNewElement('img');
img.style.height = '100px';
img.src = evt.target.result;
itemWrapper.insertBefore(img, fileInput);
}
}
}
}
.item
{
border: solid 1px black;
border-radius: 6px;
padding: 4px;
}
.button:hover
{
background-color: #b0ffb0;
cursor: pointer;
}
<div id='previewHolder' style='width: 200px'>
<div class='button' id='addBtn' style='text-align:center;padding: 4px'><svg xmlns="http://www.w3.org/2000/svg" height="32" width="32" viewBox="0 0 32 32">
<g transform="translate(0 -1020)" stroke="#00c03b" fill="none">
<circle cx="16" cy="1036" r="14.5" stroke-width="2.998"/>
<path d="m8 1036h16" stroke-linecap="round" stroke-width="3"/>
<path d="m16 1044v-16" stroke-linecap="round" stroke-width="3"/>
</g>
</svg></div>
</div>