show image file javascript code example
Example 1: preview image file upload javascript
<input type="file" accept="image/*" onchange="loadFile(event)">
<img id="output"/>
<script>
var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
output.onload = function() {
URL.revokeObjectURL(output.src)
}
};
</script>
Example 2: show image javascript
HTML:
<img id="theImage" src="yourImage.png">
<a id="showImage">Show image</a>
JavaScript:
document.getElementById("showImage").onclick = function() {
document.getElementById("theImage").style.visibility = "visible";
}
CSS:
#theImage { visibility: hidden; }
Example 3: show image javascript
JS:
function setImageVisible(id, visible) {
var img = document.getElementById(id);
img.style.visibility = (visible ? 'visible' : 'hidden');
}
HTML:
<img id="myImageId" src="yourImage.png">
Then, your links would be:
<a href="javascript:setImageVisible('myImageId', true)">show image</a>
<a href="javascript:setImageVisible('myImageId', false)">hide image</a>
CSS:
#theImage { visibility: hidden; }
Example 4: how to display image before upload in jhtml
function display(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(event) {
$('#myid').attr('src', event.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#demo").change(function() {
display(this);
});