- drag and drop behaviour is native in HTML5
- any element can be draggable using the attribute
draggable="true"
- add a listener to
- enable behaviour on an element e.g.
ondragstart="drag(event)"
- enable behaviour on a drop zone e.g.
ondragover="allowDrop(event)"
*
- enable behaviour on an element e.g.
- in the JS file define the
drag()
andallowDrop()
functionsfunction drag(event) { event.dataTransfer.setData("text", event.target.id); }
dataTransfer
holds the event's data and has methods for managing the datasetData
adds an item to the data- the value of the data is defined as
event.target.id
function allowDrop(event) { event.preventDefault(); } function drop(event) { event.preventDefault(); var data = event.dataTransfer.getData("text"); event.target.appendChild(document.getElementById(data)); }
event.preventDefault
cancels the default behaviour that prevents dropping into another element. *allowDrop
indicates a zone that can accept draggable elements.- and
drop
indicates what should happen when an element is dropped in the drop zone