<section>
<form id="filehandler">
<label for="fileUpload">Preview your image</label>
<input type="file" id="fileUpload" accept="image/*" onchange="previewImage(this)">
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/fibre-optic-tips-2x.jpg" id="imgpreview">
</form>
</section>
body {
background: #333;
}
section {
width: 80%;
max-width: 1000px;
margin: 0 auto;
}
#imgpreview {
width: 100%;
height: auto;
margin-bottom: 2rem;
}
#fileSelector {
font-size: 1.3rem; padding: .5rem 1rem;
background: hsl(50,100%,50%);
font-family: Avenir, sans-serif;
border-radius: 5px;
cursor: pointer;
display: block;
margin: 1rem auto;
}
View Compiled
var fileUpload = document.getElementById("fileUpload"),
uploadLabel = document.querySelector("label[for='fileUpload']"),
fileInsert = document.createElement("button");
fileInsert.id = "fileSelector";
fileInsert.innerHTML = uploadLabel.innerHTML;
fileUpload.parentNode.insertBefore(fileInsert, fileUpload.nextSibling);
fileUpload.style.display = "none";
uploadLabel.style.display = "none";
fileInsert.addEventListener('click', function(e){
e.preventDefault();
fileUpload.click();
}, false);
function previewImage(input) {
var preview = document.getElementById('preview');
var imgForm = document.getElementById('filehandler');
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
var imgPreview = document.getElementById('imgpreview');
imgPreview.setAttribute('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
} else {
imgPreview.setAttribute('src', 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/fibre-optic-tips-2x.jpg');
}
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.