I am trying to get similar functionality as dropbox has for drag and drop. I would like to achieve this using as basic web compoments/coding as possible. HTML or HTML5 would be best. This is for a prototype so faster the better. Here is what i am trying to achieve:
1) user should be able to drag and drop a file from their computer to anywhere on the web page. 2) The web page itself should show some indicator (ie: highlight or color overlay) when an item is dragged over it.
I have seen code snippets of several examples but they all limit to dropping containers that are already on the screen into others and not so much file into the webpage.
The dropped file does not need to be uploaded anywhere since this is going to be a demo.
Anyone have some code snippets that can get me going.
The basic idea is this:
html
element that will show the zone when something is being dragged over the page.Here is the code that worked for me: https://jsfiddle.net/oL2akhtz/.
This part of HTML5 spec is a little bit strange. The most important things to keep in mind are these:
dragenter
fires when we drag something and enter the bounds of an element; dragover
fires every few ms while we are dragging something over the element; dragleave
is the opposite of dragenter
; drop
fires when something is actually dropped.dragenter
and dragover
on any element that is a valid drop target. That is, the element is turned into a valid drop target by listening to those events and cancelling their default actions. In our case this applies to the drop-zone overlay.Now I’ll try to explain my code.
dragenter
for the whole page. It just shows the overlay (and there is no need to prevent the default action as we actually do not intend to drop anything on the page, we will be dropping only on the overlay).dragenter
and dragover
for the overlay. They prevent the default actions (which are to disallow dropping there) and also set dropEffect
to give the user some nice feedback (although this seems to do nothing right now in modern browsers). This is a good place to test whether the item being dragged is valid.div
covers everything) we hide it.That’s it, pretty straightforward. Here is what happens when someone drops a file:
dragenter
for the html
element fires. It shows the dropzone.dragleave
for the html
element fires, but we ignore it.dragenter
for the dropzone fires and then dragover
keeps firing. We just jeep saying that, yes, this is a valid drop target.drop
fires, in which case we hide the dropzone and process the file, or dragleave
for the dropzone fires in which case we just hide it.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With