Skip to content

Instantly share code, notes, and snippets.

@yakserr
Last active June 14, 2022 07:29
Show Gist options
  • Save yakserr/386e68d5a087c11af4199c8e33526067 to your computer and use it in GitHub Desktop.
Save yakserr/386e68d5a087c11af4199c8e33526067 to your computer and use it in GitHub Desktop.
Preview Image in Form
<!-- jsfiddle : https://jsfiddle.net/yakser/7ove0ky8/2/ -->
<!-- in production, please install Tailwind CSS instead of CDN -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<!-- Tailwind CSS CDN -->
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
<div class="my-6">
<div class="flex justify-start">
<div class="mb-3 w-96">
<img class="img-preview w-full h-auto rounded-md shadow-md">
<input class="form-control block w-full px-3 py-1.5 mt-1 text-base font-normal dark:text-gray-300 dark:border-gray-600 dark:bg-gray-700 bg-clip-padding border border-solid border-gray-300 rounded transition ease-in-out m-0 focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none" type="file" id="image" name="image" onchange="previewImage()">
</div>
</div>
</div>
</body>
</html>
<script>
function previewImage() {
const image = document.querySelector('#image');
const imgPreview = document.querySelector('.img-preview');
imgPreview.style.display = 'block';
const oFReader = new FileReader();
oFReader.readAsDataURL(image.files[0]);
oFReader.onload = function(oFREvent) {
imgPreview.src = oFREvent.target.result;
};
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment