Drag Drop vanilla JS

Drag Drop vanilla JS


Can someone please explain to me with comments, line by line the following methods used in this program and exactly how it works.

<title>HTML5 Drag and Drop</title> 
body {
background-color: #ddd; 
font-family: arial, verdana, sans-serif;
#drop1 {
width: 200px; 
height: 200px; 
border: 1px solid black; 
background-color: white;
#drag1 {
width: 50px; 
height: 50px; 
function allowDrop (ev) {
//normally elements dont allow drop so this prevents the default of preventing drop
function drag(ev) {
  ev.dataTransfer.setData("Text", ev.target.id) ;
//sets a data transfer property? what is going on in here?
function drop (ev) {
  var data = ev.dataTransfer.getData("Text"); 
window.onload = function() {
  var dragged = document.getElementById("drag1"); 
  var drophere = document.getElementById("drop1"); 
  dragged.ondragstart = drag; 
  drophere.ondragover = allowDrop; 
  drophere.ondrop = drop;
<div id="drop1"></div> 
<p>Drag the image below into the box above: </p>
<img id="drag1" src="drag.png" draggable="true" /> 


Can you indent the code to make it more readable? Also, why not just tell us which lines you do not understand? There is no sense in explaining a line you already understand.


Thank you for indenting. Now I can see!:grinning:


what does ev represent?
what is ‘Text’? what is ev.target.id?
what is the diff between .setData and .getData?
what is happening in the onload function?


I have not used these methods before, so I would have to read up about it and get back with you. Did you try the MDN documentation for these methods?