For an interesting visual representation, check out this fiddle
Don't worry about the CSS for now.
The main objective of this block of jQuery code is to determine the direction opposite to where the mouse initially entered into the .container
element. Despite its appearance, just focus on what it's meant to do. Directions are indicated by n (north), ne (northeast), and so forth...
If you open up the developer console and move your mouse crazily within the boundaries of the invisible div.container
, you will eventually see 'undefined' printed in the console. (The container surrounds a circular button)
An occurrence of 'undefined' only happens when x === 0 && y === 0
in the getMovementDirection()
function. This indicates that the mouse, upon entering div.container
, was already inside div.button
(the spherical button) - which should not be possible.
Hence, my question is, what's causing this behavior in the code?
-Appreciate any guidance provided
PS:
The title could use some work.
jQuery code
(function($) {
var $container = $('div.container'),
$button = $('div.button');
$container.on('mouseenter', function(e) {
var mouseLocation = {
x: e.pageX,
y: e.pageY
}
var buttonLocation = {
x: $button.offset().left,
y: $button.offset().top
}
var loc = getMovementDirection(mouseLocation, buttonLocation, jQuery);
console.log(loc);
});
})(jQuery);
function getMovementDirection (mouse, container, $) {
var width = $('div.button').outerWidth(),
height = $('div.button').outerHeight();
var x, y;
if (mouse.x < container.x) { x = -1; }
else if (mouse.x < container.x + width) { x = 0; }
else { x = 1; }
if (mouse.y < container.y) { y = -1; }
else if (mouse.y < container.y + width) { y = 0; }
else { y = 1; }
if ( x === -1 && y === -1 ) { return 'se'; }
else if ( x === 0 && y === -1 ) { return 's'; }
else if ( x === 1 && y === -1 ) { return 'sw'; }
else if ( x === -1 && y === 0 ) { return 'e'; }
// x === 0 && y === 0 is forbidden
else if ( x === 1 && y === 0 ) { return 'w'; }
else if ( x === -1 && y === 1 ) { return 'ne'; }
else if ( x === 0 && y === 1 ) { return 'n'; }
else if ( x === 1 && y === 1 ) { return 'nw'; }
}