Drag and drop image to webpage


I went over how to drag and drop an image to a webpage in my 2021-01-23 livestream:

Overview

Create a dropzone element (I used a <main> element but you can create a different element):

<main></main>
<script>
  const dropzone = document.querySelector('main');
</script>

Give the dropzone a dashed border style:

<style>
  main {
    border: 1px border lightgray;
    width: 100px;
    height: 100px;
  }
</style>

Highlight the dropzone when the dragenter event is fired (image is dragged over the dropzone):

<style>
  .active {
    border: 1px dashed black;
  }
</style>

<script>
  // ...
  dropzone.addEventListener('dragenter', event => {
    event.preventDefault();
    dropzone.classList.add('active');
  });
</script>

event.preventDefault() is necessary or else the image will be opened from your local file explorer.

Remove the dropzone highlight when the dragleave event is fired (image is no longer dragged over the dropzone):

<script>
  // ...
  dropzone.addEventListener('dragleave', event => {
    event.preventDefault();
    dropzone.classList.remove('active');
  });
</script>

It’s necessary to handle the dragover event before drop happens:

<script>
  // ...
  dropzone.addEventListener('dragover', event => {
    event.preventDefault();
  });
</script>

Now handle the drop event (when the image is released inside the dropzone):

<script>
  // ...
  dropzone.addEventListener('drop', event => {
    event.preventDefault();
    dropzone.classList.remove('active');

    const file = event.dataTransfer.files[0];
    const reader = new FileReader();
    reader.readAsDataURL(file);

    reader.addEventListener('loadend', () => {
      const img = document.createElement('img');
      img.src = reader.result;
      dropzone.append(img);
    });
  });
</script>

Here’s a breakdown of what’s happening:

  1. event.preventDefault() is called to ensure the file is not opened in the local file explorer.
  2. The dropzone highlight is removed.
  3. The image is retrieved from event.dataTransfer.files.
  4. The image is read as data URL using FileReader.
  5. The image is appended to the dropzone when it’s loaded.

Note

The dragenter and dragleave events aren’t required for drag and drop to work. They are simply there to improve user experience.

Demo

Repl.it:



Please support this site and join our Discord!