DEV Community

roadpilot
roadpilot

Posted on

Drag and drop.

This is a little sidebar from the project series and it's going to be about creating a "drag and drop" html element. This particular element isn't going to be React.js based or anything complicated but just simple HTML. I've been creating a contact tracking database tool and I've had to do a lot of manual data entry. That's just silly since the URL is very standard and the parsing from the URL is not too challenging either. Just the right combination for some automation. So, I figured, why do I need to do all of this manual data entry? I don't - and so was born the need for learning about "drag and drop". It's not terribly complicated and I'll try to break it down into as few steps as possible.

  1. Create a drop-receiving element. This can be a div, or an input field or ... really anything. I made mine a div and I placed it at the absolute right edge of my screen so I can have another screen on top of it and still have the receptacle accessible. For this div, I needed TWO specific event listeners. One for the "ondrop" event, and one for the "ondragover" event. You can either create this inline like this: DRAG HERE! Or you can add event listeners from another JavaScript source file or inline script. I prefer inline in the div itself. All of the coding is right in one place and this is just for learning anyway.
  2. The "ondrop" event is whatever action you want to take on the "dropped" resource. If you want to do some processing on the text that you drop, then you would use: "processDrop(event.dataTransfer.getData('text'))" (assuming you've defined a "processDrop" function). The "event.dataTransfer.getData('text')" is the argument that gets passed to your function. There are many ways you can capture and pass the "event" result. I wanted the text and so "getData('text')" was everything I needed. For the purposes of testing and MVP, I just put the whole result of the event for my argument. You could easily just pass "event" and get the rest in your function, if you choose.
  3. The "ondragover" event is nothing more than preventing the default action, in this way: "event.preventDefault()" That's it! Create a function that takes your argument and throw it to an alert or console.log and play with it from there. The purpose for me was to capture the text I was dragging over but you can use images, other elements, really anything. There's a whole lot more to learn about "drag and drop" but this will get you started.

Top comments (0)