HTML5
Drag and Drop
Accept dropped files with the Drag and Drop API.
By EZ4Code Team
drag-dropfiles
Code
<div id="drop" style="width:200px;height:100px;border:2px dashed #999">
Drop files here
</div>
<script>
const drop = document.getElementById("drop");
drop.addEventListener("dragover", e => {
e.preventDefault(); // allow drop
drop.classList.add("over");
});
drop.addEventListener("dragleave", () => {
drop.classList.remove("over");
});
drop.addEventListener("drop", e => {
e.preventDefault();
drop.classList.remove("over");
const files = e.dataTransfer.files;
for (const file of files) {
console.log(file.name, file.size, file.type);
}
});
</script>Explanation
The Drag and Drop API fires dragover and drop events on a target; calling preventDefault on dragover is required to allow the drop. The transferred data lives in e.dataTransfer, which holds files for native drag operations. File objects expose name, size, and type for further processing.
More HTML5 Snippets
Semantic Elements
Structure a page with header, nav, main, article, and footer.
Form Input Types
Use native HTML5 input types, validation, and datalist.
Canvas Basics
Draw shapes, lines, and text on a 2D canvas.
Video & Audio
Embed media with multiple sources and control playback.
Local & Session Storage
Persist data in the browser with the Web Storage API.
Geolocation
Get the user's position and watch for changes.