I’m using the HTML drag and drop API. When dragging an element, I want to get separate handles to the draggable element (the original element) and to the dragged element (the moveable copy of the original element).
I can’t figure out how to manipulate one without changing the other. The example below shows how both elements turn red when the drag begins
<!DOCTYPE HTML>
<html>
<head>
<style>
#div1 {
width: 350px;
height: 90px;
padding: 10px;
border: 1px solid #aaaaaa;
}
.red {
background: red;
border: 5px solid #aaaaaa;
}
#drag1 {
height: 69px;
width: 336px;
border: 5px solid #aaaaaa;
}
</style>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.target.classList.add('red');
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">drop here</div>
<br>
<div id="drag1" draggable="true" ondragstart="drag(event)" width="336" height="69">drag me</div>
</body>
</html>
2
Answers
If you use
ondrag
instead ofondragstart
, you can make the elements different, but you can only change the state of the original element (the dragged element will be the previous state before the drag, so it looks exactly as the moment before you start dragging).Create a custom drag image: Use the setDragImage method to create and set a custom drag image, so you can keep the original element unchanged.
Handle the dragstart and dragend events: Manipulate the original element and apply changes only to it.
CSS code here:-
JavaScript Code below:
HTML code below: