Skip to content

Instantly share code, notes, and snippets.

@korof
Created August 19, 2015 06:46
Show Gist options
  • Save korof/82aaa0d7c62b0bfda9b1 to your computer and use it in GitHub Desktop.
Save korof/82aaa0d7c62b0bfda9b1 to your computer and use it in GitHub Desktop.
var getDir = function( elem, e ) {
/** the width and height of the current div **/
var w = elem.width();
var h = elem.height();
var offset = elem.offset();
/** calculate the x and y to get an angle to the center of the div from that x and y. **/
/** gets the x value relative to the center of the DIV and "normalize" it **/
var x = (e.pageX - offset.left - (w/2)) * ( w > h ? (h/w) : 1 );
var y = (e.pageY - offset.top - (h/2)) * ( h > w ? (w/h) : 1 );
/** first calculate the angle of the point,
add 180 deg to get rid of the negative values
divide by 90 to get the quadrant
add 3 and do a modulo by 4 to shift the quadrants to a proper clockwise TRBL (top/right/bottom/left) **/
var direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180 ) / 90 ) + 3 ) % 4;
/** return the direction **/
switch(direction) {
case 0:
return 'top';
break;
case 1:
return 'right';
break;
case 2:
return 'bottom';
break;
case 3:
return 'left';
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment