Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript/jQuery drag and drop element between two iframes

I have a page with 2 iframes, side by side, both from the same domain. I want to drag'n'drop an element from a specific drag-zone (e.g. a table) of one iframe to a specific dropzone (e.g. a list) on the other. I checked all related questions on stackoverflow and elsewhere, but I can't find an appropriate solution. I tried it with jQuery UI draggable, but the problem is that the returned draggable element is contained within the iframe. I cannot drag it out of the iframe boundaries. So, my next thought was to create the draggable element on top (parent) window, but then I guess I'd have to somehow trigger a drag event on the parent window from the dragstart event on the iframe. But then, how would I detect the drop event when I mouse over the appropriate elements on the drop-frame?

Oh, and if that's not hard enough already, I'd like to make it work on IE8 too :) But for now, let's just say that I will find a fallback solution for IE8 that will not involve drag'n'drop.

like image 329
AsGoodAsItGets Avatar asked Jan 09 '23 18:01

AsGoodAsItGets


1 Answers

You can simulate dragging by sending mouse messages from the iframes to the parent, and doing the drag in the parent. Here is a codepen showing dragging list items from one frame to another: http://codepen.io/brenzy/details/zxMZmO/

Since SO wants some code, here is the dragHandler talking to the parent:

$("li").mousedown(function (event) {
  dragElement = $(this);
  if(event.stopPropagation) event.stopPropagation();
  if(event.preventDefault) event.preventDefault();
  event.cancelBubble=true;
  event.returnValue=false;
  return false;
});

$(document).mousemove(function (event) {
  if (dragElement) {
    if (!dragStarted) {
      // tell the parent to start dragging the item
      parent.postMessage({
        action: "dragStart", frame: myId,
        itemText: dragElement.text(), itemId: dragElement.attr('id'),
        offset: {left: event.pageX, top: event.pageY}
      }, '*');
      dragStarted = true;
    } else {
      parent.postMessage({action: "dragMove", frame: myId,
        offset: {left: event.pageX, top: event.pageY}}, '*');
    }
  }
});

$(document).mouseup(function (event) {
  if (dragStarted) {
    parent.postMessage({
      action: "cancelDrag", frame: myId,
      itemText: dragElement.text(), itemId: dragElement.attr('id'),
      offset: {left: event.pageX, top: event.pageY}
    }, '*');
  }
  dragStarted = false;
  dragElement = null;
});

NOTE: This only works in Chrome, but I am pretty sure that you can get it working in other browsers.

like image 162
brenzy Avatar answered Jan 18 '23 04:01

brenzy