htmlcssdraggable

Allow drag and drop of an element containing an iframe


I'm trying to have a very basic drag and drop. It's working fine by just setting draggable = "true", but doesn't seem to work when the draggable element contains an iframe.

I have searched everywhere and met many complex problems with iframes, but none being about my specific problem.

As you can see, only the area that is not covered by the iframe is draggable, while I would want to drag the whole container.

div {
    width: 300px;
    height: 100px;
    background: #A1DB6A;
}
iframe {
    border: 0;
    height: 80px;
    width: 100%;
    background: #ddd;
}
<div draggable="true">
    <iframe src=""></iframe>
</div>
<br/>
<span>Only the green handle is draggable, but I want the whole container to be.</span>


Solution

  • The Problem:

    An iframe contains a completely separate window from the parent window. When a user interacts with an iframe, the parent window no longer receives user events. The browser assumes you want to interact with the contents of the iframe, and ignores any draggable attributes that may be on a parent of the iframe.


    A Workaround:

    You could position an invisible element over the iframe to prevent the user from interacting with the iframe below. Here is an example using an absolute-positioned pseudo-element.

    Example CSS (JSFiddle):

    div {
        width: 300px;
        height: 100px;
        background: #A1DB6A;
        position: relative;/*parent must have positioning*/
    }
    iframe {
        border: 0;
        height: 80px;
        width: 100%;
        background: #ddd;
    }
    /*Cover up the entire element (could be limited to just covering the iframe element)*/
    div:after {
        content: "";
        display: block;
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
    }
    

    This workaround brings with it the obvious side-effect of preventing the user from interacting with the contents of the iframe, which is presumably alright in most cases where you want the element to be draggable.

    If the iframe needs to be interacted with, you could make a toggle between draggable and not-draggable, and only apply this CSS when draggable. Otherwise you would need to use JavaScript to interact with the iframe, either by contentWindow if they satisfy Same-Origin Policy, or by postMessage, and toggle it on/off based on certain events.