To make an object draggable in vanilla JS, you can use the HTML5 drag-and-drop API.
First, you need to add event listeners to the object that will be dragged, using the dragstart
, drag
, and dragend
events. Then, you need to define a drop zone using the dragover
and drop
events on the container where you want to drop the object.
Here is a simple example:
1275 chars56 lines
In this example, the draggable
element is a red square that can be dragged to the body of the page (which is the drop zone).
The dragstart
event sets the data that is being transferred during the drag operation, and also changes the opacity of the element so it looks like it's being dragged. The drag
event can be used to do something while the element is being dragged, and the dragend
event restores the opacity of the element once the drag operation is finished.
The dragover
event prevents the default action of the browser when the draggable element is being dragged over the drop zone, and the drop
event appends the dragged element to the drop zone.
gistlibby LogSnag