gsamaras
gsamaras

Reputation: 73366

Get position of dragable object, relative to a div

Here is the jsFiddle, where I have a football field, where the user shall partition 10 players, in two five-membered teams. I want to know whether he dragged a player on the left or night side (assuming the center line of the field is border).

Here the js code:

$(".dragNdrop").draggable({
  drag: function(){
    var offset = $(this).offset();
    var xPos = offset.left;
    var yPos = offset.top;
      console.log('x: ' + xPos);
      console.log($('#footballField').width());
    }
});

I've also tried with position() and offset(), but I can't seem to find the right formula to do it.

So, how will I find whether the players is positioned in the left or the right side of the div?

Related question: How to get the position of a draggable object

Upvotes: 0

Views: 55

Answers (1)

JavierFromMadrid
JavierFromMadrid

Reputation: 621

If $('#footballField').width() is the width of the field, you can check if the xPos of the dragNdrop element is less or higher than the footballField left + his width divided by 2:

$(".dragNdrop").draggable({
    drag: function(){
        var offset = $(this).offset();
        var xPos = offset.left;
        var yPos = offset.top;
        console.log('x: ' + xPos);
        //console.log('y: ' + yPos);
        console.log('offset: ' + $('#footballField').offset().left);
        var fieldLeft = $('#footballField').offset().left;
        console.log($('#footballField').width());
        if(xPos < fieldLeft + $('#footballField').width()/2){
             console.log('I am at left');
        }else{
            console.log('I am at right');
        }

    }
});

Upvotes: 1

Related Questions