0

Here is my code, where I'm trying to detect the element, which a jQuery UI draggable is hovering over. I need to get the element's object and attributes, such as class names (in this case .sortable-grid,.sortable-table,.sortable-row,.sortable-cell).

The answers found here only show how to get the draggable item itself (ui.helper or event.target), but not the element it is hovering above.

The best way to answer would be using the prepared JSFiddle, since my code uses an iframe, which would not work if the full code is posted here:

JSFiddle

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0-beta.1/jquery-ui.js"></script>

<div style="background-color:grey;display:inline;cursor:move" id="draggable">DRAG ME</div>
<iframe src="https://fiddle.jshell.net/piglin/UAcC7/1869/show/" id="frame" style="width:100%;overflow:visible" seamless="seamless" scrolling="no"></iframe>

JS:

$("#draggable").draggable({
    drag: function(event, ui) {
        //Some code here
    }
}
Kara
  • 6,115
  • 16
  • 50
  • 57
Peter G.
  • 7,816
  • 20
  • 80
  • 154

1 Answers1

0

It was possible by modifying the function from another answer to fit this purpose. After adapting it to use the contentWindow of the iframe and adding offset calculation it works now.

Solution

function allElementsFromPointIframe(x, y, offsetX, offsetY) {
  var element, elements = [];
  var old_visibility = [];
  while (true) {
    element = document.getElementById('frame').contentWindow.document.elementFromPoint(x - offsetX, y - offsetY);
    if (!element || element === document.getElementById('frame').contentWindow.document.documentElement) {
      break;
    }
    elements.push(element);
    old_visibility.push(element.style.visibility);
    element.style.visibility = 'hidden'; // Temporarily hide the element (without changing the layout)
  }
  for (var k = 0; k < elements.length; k++) {
    elements[k].style.visibility = old_visibility[k];
  }
  elements.reverse();
  return elements;
}

var selected = $('');
var tmpColor = 'transparent';
$("#draggable").draggable({
  drag: function(event, ui) {
    var el = $(allElementsFromPointIframe(event.pageX, event.pageY, $(frame).offset().left, $(frame).offset().top));
    var div = $(el).filter('ul, li').not($(this));
    selected.css({'backgroundColor': tmpColor});
    selected = div.last()
    tmpColor = selected.css('backgroundColor');
    selected.css({'backgroundColor': 'red'});
    console.dir(div);
  },
  iframeFix: true,
  iframeOffset: $('#iframe').offset()
});
Community
  • 1
  • 1
Peter G.
  • 7,816
  • 20
  • 80
  • 154