Drag Drop vanilla JS

Drag Drop vanilla JS
0

#1

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

<!DOCTYPE HTML> 
<html> 
<head>
<title>HTML5 Drag and Drop</title> 
<style>
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; 
} 
</style> 
<script>
function allowDrop (ev) {
  ev.preventDefault();
}
//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"); 
  ev.target.appendChild(document.getElementById(data)); 
  ev.preventDefault();
}
window.onload = function() {
  var dragged = document.getElementById("drag1"); 
  var drophere = document.getElementById("drop1"); 
  dragged.ondragstart = drag; 
  drophere.ondragover = allowDrop; 
  drophere.ondrop = drop;
}
</script> 
</head> 
<body>
<div id="drop1"></div> 
<p>Drag the image below into the box above: </p>
<img id="drag1" src="drag.png" draggable="true" /> 
</body> 
</html>

#2

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.


#3

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


#4

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?


#5

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?