Created
January 9, 2024 12:59
-
-
Save erdum/77bfbdc3f04378e7e5f334073b339bfb to your computer and use it in GitHub Desktop.
Image Preview Uploader
This file contains 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
<div class="col-span-6"> | |
<!-- <label class="block ml-2 text-sm font-medium text-gray-700"> Photo </label> --> | |
<div class="mt-1 flex items-center"> | |
<span class="inline-block h-36 w-36 rounded-full overflow-hidden bg-gray-100"> | |
<svg class="h-full w-full text-gray-300" fill="currentColor" viewBox="0 0 24 24"> | |
<path d="M24 20.993V24H0v-2.996A14.977 14.977 0 0112.004 15c4.904 0 9.26 2.354 11.996 5.993zM16.002 8.999a4 4 0 11-8 0 4 4 0 018 0z" /> | |
</svg> | |
</span> | |
<img src="" class="hidden h-36 w-36 rounded-full overflow-hidden object-fit"> | |
<button onclick="handleImage(this)" type="button" class="ml-5 bg-white py-2 px-3 border border-gray-300 rounded-md shadow-sm text-sm leading-4 font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">Change</button> | |
</div> | |
<input type="file" name="photo" class="hidden"> | |
</div> | |
<script> | |
function handleImage(elem) { | |
const fileInput = document.querySelector("[name=photo]"); | |
fileInput.addEventListener("change", ({ currentTarget: { files }}) => { | |
const fileReader = new FileReader(); | |
fileReader.readAsDataURL(files[0]); | |
fileReader.onload = () => { | |
const image = elem.previousElementSibling; | |
const placeholder = image.previousElementSibling; | |
image.setAttribute("src", fileReader.result); | |
image.classList.remove("hidden"); | |
placeholder.classList.add("hidden"); | |
} | |
}); | |
fileInput.click(); | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment