Last active
July 6, 2024 09:41
-
-
Save fathulfahmy/1abc3003d8ffdcd16877750196361a90 to your computer and use it in GitHub Desktop.
file input image preview
This file contains hidden or 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
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