Skip to content

Instantly share code, notes, and snippets.

@ezetojo
Created February 19, 2022 17:21
Show Gist options
  • Save ezetojo/755ba0e65e2fa5aaac440b5418ea71fa to your computer and use it in GitHub Desktop.
Save ezetojo/755ba0e65e2fa5aaac440b5418ea71fa to your computer and use it in GitHub Desktop.
Multiple inputs for image upload placeholder with preview
let filePickers = document.getElementsByClassName("file-picker");
if(filePickers){
for(let i = 0; i < filePickers.length; i++){
filePickers[i].addEventListener("change", function () {
getImgData(filePickers[i]);
});
}
}
function getImgData(filePicker) {
let imgPreview = filePicker.querySelector(".img-preview");
let imgPlaceholder = filePicker.querySelector(".img-placeholder");
let files = filePicker.querySelector("input").files[0];
if (files) {
let fileReader = new FileReader();
fileReader.readAsDataURL(files);
fileReader.addEventListener("load", function () {
imgPlaceholder.style.display = "none";
imgPreview.style.display = "flex";
imgPreview.style.backgroundImage = `url(${this.result})`;
});
}
}
<div class="mb-4 mr-4 w-full md:w-1/4 inline-block px-6 img-input">
<span for="image" class="text-xs text-gray-500">IMAGE</span>
<div class="relative overflow-hidden mt-1 mb-2 flex items-center justify-center w-full aspect-1 rounded-full bg-gray-600 text-gray-400 text-7xl img-placeholder">
<svg xmlns="http://www.w3.org/2000/svg" class="w-1/3 h-auto block" fill="currentColor" viewBox="0 0 16 16">
<path d="M6.002 5.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0z"/>
<path d="M2.002 1a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2h-12zm12 1a1 1 0 0 1 1 1v6.5l-3.777-1.947a.5.5 0 0 0-.577.093l-3.71 3.71-2.66-1.772a.5.5 0 0 0-.63.062L1.002 12V3a1 1 0 0 1 1-1h12z"/>
</svg>
</div>
<div class="relative bg-cover bg-center bg-no-repeat overflow-hidden hidden mt-1 mb-2 items-center justify-center w-full aspect-1 img-preview"></div>
<input type="file" accept="image/png, image/jpeg" class="text-xs bg-gray-100 border-0 focus:ring-0 mt-1 p-2 rounded block w-full outline-none transition focus:bg-gray-200 focus:shadow-inner" name="image">
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment