Skip to content

Instantly share code, notes, and snippets.

@w3collective
Created June 28, 2021 23:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save w3collective/e0f8dd9d184657ada35adf83bb77921f to your computer and use it in GitHub Desktop.
Save w3collective/e0f8dd9d184657ada35adf83bb77921f to your computer and use it in GitHub Desktop.
Preview selected image (input type=”file”) using JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Preview selected image (input type=”file”) using JavaScript</title>
<style>
body {
padding: 1em 0 0 1em;
}
#img-preview {
display: none;
width: 155px;
border: 2px dashed #333;
margin-bottom: 20px;
}
#img-preview img {
width: 100%;
height: auto;
display: block;
}
[type="file"] {
height: 0;
width: 0;
overflow: hidden;
}
[type="file"] + label {
font-family: sans-serif;
background: #f44336;
padding: 10px 30px;
border: 2px solid #f44336;
border-radius: 3px;
color: #fff;
cursor: pointer;
transition: all 0.2s;
}
[type="file"] + label:hover {
background-color: #fff;
color: #f44336;
}
</style>
</head>
<body>
<form>
<div>
<div id="img-preview"></div>
<input
type="file"
accept="image/*"
id="choose-file"
name="choose-file"
/>
<label for="choose-file">Choose File</label>
</div>
</form>
<script>
const chooseFile = document.getElementById("choose-file");
const imgPreview = document.getElementById("img-preview");
chooseFile.addEventListener("change", function () {
getImgData();
});
function getImgData() {
const files = chooseFile.files[0];
if (files) {
const fileReader = new FileReader();
fileReader.readAsDataURL(files);
fileReader.addEventListener("load", function () {
imgPreview.style.display = "block";
imgPreview.innerHTML = '<img src="' + this.result + '" />';
});
}
}
</script>
</body>
</html>
@w3collective
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment