Categories
JavaScript Answers

How to prevent browser from loading a drag-and-dropped file with JavaScript?

Spread the love

To prevent browser from loading a drag-and-dropped file with JavaScript, we stop the default behavior for the dragover and drop events.

For instance, we write

window.addEventListener(
  "dragover",
  (e) => {
    e.preventDefault();
  },
  false
);

window.addEventListener(
  "drop",
  (e) => {
    e.preventDefault();
  },
  false
);

to call addEventListener to add event listeners for the window’s dragover and drop events.

In the event handlers, we call e.preventDefault to stop the default drtag and drop behavior to stop the loading of dragged and dropped files.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *