• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Highlight an element when dragging a file over it

Highlight an element when dragging a file over it

Highlight an element when dragging a file over it

Assume that we have a droppable element as below:

<div id="droppable">...</div>

We will highlight the element when user drags a file over it. For example, the element will have a dashed border which can be simulated by a CSS class:

.dragging {
    border: 4px dashed #ccc;
}

The dragging class will be added to the element when user drags file and moves it over the element:

// Query the element
const ele = document.getElementById('droppable');

ele.addEventListener('dragenter', function (e) {
    e.preventDefault();
    e.target.classList.add('dragging');
});

In similar events, the class is removed from the element when user moves the file out of the element, or drops it:

ele.addEventListener('dragover', function (e) {
    e.preventDefault();
});

ele.addEventListener('dragleave', function (e) {
    e.preventDefault();
    e.target.classList.remove('dragging');
});

ele.addEventListener('drop', function (e) {
    e.preventDefault();
    e.target.classList.remove('dragging');
});

The last thing, e.preventDefault() is used in the handlers to prevent the browser from executing the default action.

Source

https://htmldom.dev/highlight-an-element-when-dragging-a-file-over-it/

Miscellaneous

Related Snippets:

  • Detect Internet Explorer browser
  • Copy a segment of an array into a new array
  • Get and set the text of an element (without markup)
  • Prevent the default action of an event

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers