'How to make reposition/move IFrame element with mouse drag?

I would like to reposition the iframe element on a website through mouse drag.

Dynamically Created IFrame Element

    // create div to hold iframe
    let iframeContainer = document.createElement("div");
    iframeContainer.style.all = "revert";
    iframeContainer.style.position = "absolute";

    // create iframe element
    let iframe = document.createElement("iframe");
    iframe.width = "400";
    iframe.height = "400";
    iframe.style.border = "0px";

    // append iframe element to document.body
    document.body.appendChild(iframeContainer);
    iframeContainer.appendChild(iframe);

Functions to Enable HTML Element Dragging

function dragIFrameElement(elementToMove, dragControllerElement) {
    var pos1 = 0,
        pos2 = 0,
        pos3 = 0,
        pos4 = 0;

    dragControllerElement.onmousedown = dragMouseDown;

    function dragMouseDown(e) {
        e = e || window.event;
        e.preventDefault();
        // get the mouse cursor position at startup:
        pos3 = e.clientX;
        pos4 = e.clientY;
        document.onmouseup = closeDragElement;
        // call a function whenever the cursor moves:
        document.onmousemove = elementDrag;
    }

    function elementDrag(e) {
        e = e || window.event;
        e.preventDefault();
        // calculate the new cursor position:
        pos1 = pos3 - e.clientX;
        pos2 = pos4 - e.clientY;
        pos3 = e.clientX;
        pos4 = e.clientY;

        // set the element's new position:
        // elementToMove.style.top = elementToMove.offsetTop - pos2 + "px";
        // elementToMove.style.left = elementToMove.offsetLeft - pos1 + "px";
        elementToMove.style.setProperty(
            "top",
            elementToMove.offsetTop - pos2 + "px",
            "important"
        );
        elementToMove.style.setProperty(
            "left",
            elementToMove.offsetLeft - pos1.toString() + "px",
            "important"
        );
    }

    function closeDragElement() {
        // stop moving when mouse button is released:
        document.onmouseup = null;
        document.onmousemove = null;
    }
}

This code works on normal HTML div element, but it doesn't work as expected in my iframeContainer.

What ended happening is that there seems to always be some offset between my current mouse position and the dragged iframeContainer. It is moving with my mouse as I try to drag it, but there's always like a very big gap in between.

Usage

let innerDoc = iframe.contentDocument || iframe.contentWindow.document;
// navbar is just an element inside my iframe
let navbar = innerDoc.getElementsByClassName("notecard-navbar")[0];
dragIFrameElement(iframeContainer, navbar);

Any help would be much appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source