How to move / drag element from outside to iframe?

Member

by deron , in category: HTML & CSS , 2 months ago

How to move / drag element from outside to iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 2 months ago

@deron 

To move or drag an element from outside the iframe to inside it, you can achieve this by following these steps:

  1. Identify the element you want to drag from outside the iframe. This element should be draggable, so you may need to set the draggable attribute to true.
  2. Add event listeners to capture when dragging starts, moves, and ends. You can use the dragstart, dragover, and drop events for this purpose.
  3. When the drag starts, store the information of the element being dragged, such as its position and size.
  4. When the element is dragged over the iframe, capture the drop event and retrieve the position of the mouse cursor relative to the iframe. You can do this by subtracting the iframe's position from the mouse cursor's position.
  5. Calculate the new position of the element inside the iframe based on the mouse cursor's position and the information stored in step 3.
  6. Move the element to the new position inside the iframe.


Here's an example code snippet to demonstrate how you can achieve this using JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE html>
<html>
<head>
<style>
#draggable {
  width: 100px;
  height: 100px;
  background-color: red;
  position: absolute;
}
</style>
</head>
<body>

<div id="draggable" draggable="true" ondragstart="drag(event)">Drag me!</div>

<iframe id="myiframe" src="iframe.html" style="width: 300px; height: 300px;"></iframe>

<script>
function drag(event) {
  event.dataTransfer.setData("text", event.target.id);
}

document.querySelector('#myiframe').contentWindow.document.body.ondragover = function(event) {
  event.preventDefault();
}

document.querySelector('#myiframe').contentWindow.document.body.ondrop = function(event) {
  event.preventDefault();
  var data = event.dataTransfer.getData("text");
  var element = document.getElementById(data);
  var iframeRect = document.querySelector('#myiframe').getBoundingClientRect();
  var x = event.clientX - iframeRect.left;
  var y = event.clientY - iframeRect.top;
  element.style.position = 'absolute';
  element.style.left = x + 'px';
  element.style.top = y + 'px';
  event.target.appendChild(element);
}
</script>

</body>
</html>


In this example, we have a draggable element outside the iframe. When this element is dragged and dropped inside the iframe, its position is calculated based on the mouse cursor's position relative to the iframe, and then the element is moved to that position inside the iframe.