draggable object in vannilla js in javascript

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:

<!DOCTYPE html>
<html>
<head>
	<title>Draggable Object Example</title>
	<style type="text/css">
		#draggable {
			width: 100px;
			height: 100px;
			background-color: red;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			cursor: move;
		}
	</style>
</head>
<body>

	<div id="draggable"></div>

	<script type="text/javascript">
		// Get the draggable element
		var draggable = document.getElementById("draggable");

		// Add event listeners for the drag events
		draggable.addEventListener("dragstart", function(event) {
			event.dataTransfer.setData("text/plain", event.target.id);
			event.target.style.opacity = "0.5";
		});

		draggable.addEventListener("drag", function(event) {
			// Do something while dragging
		});

		draggable.addEventListener("dragend", function(event) {
			event.target.style.opacity = "1";
		});

		// Get the drop zone element
		var container = document.body;

		// Add event listeners for the drop events
		container.addEventListener("dragover", function(event) {
			event.preventDefault();
		});

		container.addEventListener("drop", function(event) {
			var data = event.dataTransfer.getData("text/plain");
			event.target.appendChild(document.getElementById(data));
		});
	</script>

</body>
</html>
1275 chars
56 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