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

Estimated read time 1 min read

To prevent the browser from loading a drag-and-dropped file with JavaScript, you can listen for the dragover and drop events, and call the preventDefault() method on their event objects.

Here’s an example:

window.addEventListener("dragover", function(event) {
  event.preventDefault();
});

window.addEventListener("drop", function(event) {
  event.preventDefault();
});

In this example, the dragover and drop events are listened for on the window object. When either of these events is triggered, the preventDefault() method is called on its event object, which cancels the default behavior (in this case, loading the dragged file).

This will prevent the browser from loading any files that are dragged and dropped onto the page. If you want to allow some files to be loaded, you can add additional logic to the event handlers to only prevent the default behavior under certain conditions.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply