Skip to content

Instantly share code, notes, and snippets.

@fathulfahmy
Last active July 6, 2024 09:41
Show Gist options
  • Save fathulfahmy/1abc3003d8ffdcd16877750196361a90 to your computer and use it in GitHub Desktop.
Save fathulfahmy/1abc3003d8ffdcd16877750196361a90 to your computer and use it in GitHub Desktop.
file input image preview
function previewImage() {
const dropZone = document.getElementById("drop-zone");
const fileInput = document.getElementById("file-input");
const img = document.getElementById("preview-image");
let p = document.getElementById("drop-text");
if (fileInput) {
fileInput.addEventListener("change", function () {
const clickFile = this.files[0];
if (clickFile) {
img.style = "display:block;";
if (p) {
p.style = "display: none";
}
const reader = new FileReader();
reader.readAsDataURL(clickFile);
reader.onloadend = function () {
let src = this.result;
img.src = src;
img.alt = clickFile.name;
};
}
});
}
if (dropZone) {
dropZone.addEventListener("click", () => fileInput.click());
dropZone.addEventListener("dragover", (e) => {
e.preventDefault();
});
dropZone.addEventListener("drop", (e) => {
e.preventDefault();
img.style = "display:block;";
let file = e.dataTransfer.files[0];
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = function () {
e.preventDefault();
p.style = "display: none";
let src = this.result;
img.src = src;
img.alt = file.name;
};
});
}
}
window.onload = previewImage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment