0

So I have a draggable object- How can I test if its stop position is in a certain range (over a div)

best i can do is find its exact position. Thanks.

Fiddle http://jsfiddle.net/f5n66/

 $( init );

function init() {
  $('.draggable').draggable({
  opacity:0.7, helper:"clone",
  stop: function(event, ui) {
    if(ui.position === $('#resultArea').position()){
        console.log(ui.position);
        }
}
  });

}

lpoulter
  • 158
  • 9

1 Answers1

1

You need to check if the drop is inside the dimension of the dropzone div.

function init() {
  $('.draggable').draggable({
  opacity:0.7, helper:"clone",

  stop: function(event, ui) {
      var coords = $('#resultArea').position();
      coords.bottom = coords.top + $('#resultArea').height();
      coords.bottomRight = coords.left + $('#resultArea').width();
        if(ui.position.top >= coords.top && ui.position.top <= coords.bottom && ui.position.left >= coords.left && ui.position.left <= coords.bottomRight){
            console.info("inside");
        }else{
             console.info("outside");   
        }
    }
      });
}

Live Demo

Update: Place the calculations in a separate function to make it reusable

function inDropZone(drag, drop){
    var coords = drop.position();
    coords.bottom = coords.top + drop.height();
    coords.bottomRight = coords.left + drop.width();
    if(drag.position.top >= coords.top && drag.position.top <= coords.bottom && drag.position.left >= coords.left && drag.position.left <= coords.bottomRight){
        return true;
    }else{
         return false;
    }
}
Stevanicus
  • 7,561
  • 9
  • 49
  • 70