Skip to content

Instantly share code, notes, and snippets.

@Quinten
Created August 17, 2021 13:48
Show Gist options
  • Save Quinten/8a9f4f0f70afaa7089803adbaa869c7f to your computer and use it in GitHub Desktop.
Save Quinten/8a9f4f0f70afaa7089803adbaa869c7f to your computer and use it in GitHub Desktop.
Detect mouse direction and cancel hovers
// depends on modernizr and jquery
if ($('html').hasClass('no-touchevents')) {
var hoverDelay = 17;
var hoverTimeouts = [];
var hoverDelayTO = 0;
function processHoverTimeouts () {
hoverTimeouts.forEach(function (timeout) {
timeout();
});
hoverTimeouts = [];
}
function addHoverTimeout (timeout) {
hoverTimeouts.push(timeout);
clearTimeout(hoverDelayTO);
hoverDelayTO = setTimeout(processHoverTimeouts, hoverDelay);
}
var time = Date.now();
var mX = 0;
var mY = 0;
$('body').on('mousemove', function (e) {
var delta = Date.now() - time;
var mA = 0; // mouse direction (in radians)
if (delta >= 40) {
if (e.pageY == mY && e.pageX == mX) {
return;
}
mA = Math.atan2(e.pageY - mY, e.pageX - mX);
mX = e.pageX;
mY = e.pageY;
}
if (hoverTimeouts.length && mA < 1.5 && mA > -1.5) {
clearTimeout(hoverDelayTO);
hoverDelayTO = setTimeout(processHoverTimeouts, hoverDelay);
}
});
$('li.on-the-side').on('mouseleave', function (e) {
var el = $(e.currentTarget);
if (window.innerWidth < 1024) {
return true;
}
addHoverTimeout(function () {
el.parents('ul').find('li.on-the-side').removeClass('is-active');
});
});
$('li.on-the-side').on('mouseenter', function (e) {
var el = $(e.currentTarget);
if (window.innerWidth < 1024) {
return true;
}
addHoverTimeout(function () {
el.addClass('is-active');
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment