In this blog we are going to see how to do drag and drop and preview the image.

Step1:

first we ll design the html page like below.

<div id="drophere">
  <p>Drag files here and check the console.</p>
</div>


<div id="imgList">
  
</div>

 

 

Step2:

below is the css properties:

#drophere {
  background-color:#ccc; 
  width:100%;
  height:250px;
  font-family: sans-serif;
}

#drophere.highlight{
   background-color:red;
}
img{
  width:20%
}

Javascript:

in JS we have 4 events for drag and drop.

 

dragenter when drag is entered
dragover when we hover on the drag element
drop after we drop the object in the drag element
dragleave when we leave from drag element

 

usins above events we are going to implement the javascript.

 

 

let dropElement;

dropElement = document.getElementById("drophere");
dropElement.addEventListener("dragenter", dragenter, false);
dropElement.addEventListener("dragover", dragover, false);
dropElement.addEventListener("drop", drop, false);
dropElement.addEventListener("dragleave",dragleave);

function dragenter(e) {
  e.stopPropagation();
  e.preventDefault();

//adding the highlight class while enter for dropping
  dropElement.classList.toggle("highlight");
}

function dragover(e) {
  e.stopPropagation();
  e.preventDefault();

function dragleave(e) {
  e.stopPropagation();
  e.preventDefault();

//removing the highlight class while leaving from the dropped place.

 droppingdropElement.classList.toggle("highlight");

function drop(e) {
  e.stopPropagation();
  e.preventDefault();
  dropElement.classList.toggle("highlight");
  const dt = e.dataTransfer;
  const files = dt.files;

 
  for (let file in files){
     let reader = new FileReader();
  reader.readAsDataURL(files[file])
  reader.onloadend = function() {
    let img = document.createElement('img')
    img.src = reader.result;
    document.getElementById('imgList').appendChild(img)
  }
  }
}

Source Code gitHub Link

HTML output: