Preview image before upload using JavaScript

In this tutorial, we will be learning to preview an image without actually uploading it to the server. We will use couple of lines of JavaScript code to achieve this.

HTML Code:

<img class="image-preview">
<div class="button_outer">
  <div class="btn_upload">
    <input type="file" class="upload-photo">
    Upload Image
  </div>
</div>

CSS Code:

body{
  display: flex;
  justify-content: center;
  align-items: center;
  height:100vh;
  flex-direction: column;
}
img.image-preview[src='']{
  display: none;
}
.button_outer {
  background: #83ccd3; 
  border-radius:30px; 
  text-align: center; 
  height: 50px; 
  width: 200px; 
  display: inline-block; 
  transition: .2s; 
  position: relative; 
  overflow: hidden;
}

.btn_upload {
  padding: 17px 30px 12px; 
  color: #fff; 
  text-align: center; 
  position: relative; 
  display: inline-block; 
  overflow: hidden; 
  z-index: 3; 
  white-space: nowrap;
}
.btn_upload input {
  position: absolute; 
  width: 100%; 
  left: 0; 
  top: 0; 
  width: 100%; 
  height: 105%; 
  cursor: pointer; 
  opacity: 0;
}

JavaScript Code:

document.getElementsByClassName('upload-photo')[0].onchange = function () {
  var src = URL.createObjectURL(this.files[0]);
  document.getElementsByClassName('image-preview')[0].src = src;
}
document.getElementsByClassName('image-preview')[0].onclick = function() {
  document.getElementsByClassName('upload-photo')[0].click();
}
RH Suman
RH Suman
Articles: 64

Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a Reply