Reputation: 73366
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
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