Drag and Drop a File

by Génesis García Morilla

HTML

<div>DROP HERE</div>

CSS

body {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  display: grid;
  justify-content: center;
  align-items: center;
}

div {
  width: 50vw;
  height: 60vh;
  background-color: grey;
  font-size: 5vw;
  color: white;
  display: grid;
  justify-content: center;
  align-items: center;
  background-size: cover;
}

JavaScript

const $div = document.querySelector('div')

$div.ondragover = e => e.preventDefault() // prevent default browser behavior

$div.ondrop = e => {  
  const file = e.dataTransfer.files[0] // we are gonna take just the first one
  $div.style.backgroundImage = `url(${URL.createObjectURL(file)})`
}