Skip to content

Instantly share code, notes, and snippets.

@damianwajer
Last active July 20, 2020 09:29
Show Gist options
  • Save damianwajer/32136afff2cc8d91dc161f455462631a to your computer and use it in GitHub Desktop.
Save damianwajer/32136afff2cc8d91dc161f455462631a to your computer and use it in GitHub Desktop.
[JavaScript][jQuery] Close the navigation with swipe gestures.
/**
* Get navigation position.
*
* @param {jQuery} $nav Navigation element.
* @returns {string} Navigation position (left, right or fullwidth).
*/
function getNavigationMode($nav) {
let offset = $nav.offset();
let distanceLeft = Math.round(offset.left - $(document).scrollLeft());
let distanceRight = Math.round($(window).width() - distanceLeft - $nav.width());
if (distanceLeft <= 0 && distanceRight > 0) {
return "left";
} else if (distanceLeft > 0 && distanceRight <= 0) {
return "right";
}
return "fullwidth";
}
/**
* Close the navigation with swipe gestures within the navigation and its background.
*
* @param {jQuery} $nav Navigation element.
*/
function swipeToClose($nav) {
const $elements = $nav.add(".backdrop");
let touchStartX = 0;
let touchStartY = 0;
let touchMoveEndX = 0;
let touchMoveEndY = 0;
let isClosing = false;
$elements.each(function (i, el) {
const $el = $(el);
$el.on("touchstart", function (e) {
isClosing = false;
touchStartX = e.originalEvent.touches[0].clientX;
touchStartY = e.originalEvent.touches[0].clientY;
});
$el.on("touchmove", function (e) {
touchMoveEndX = e.originalEvent.touches[0].clientX;
touchMoveEndY = e.originalEvent.touches[0].clientY;
const threshold = 20 // prevent accidental closing with gentle gestures
const xDiff = touchStartX - touchMoveEndX;
const yDiff = touchStartY - touchMoveEndY;
if (Math.abs(xDiff) > Math.abs(yDiff) && Math.abs(xDiff) >= threshold) { // horizontal swipe
const navigationPosition = getNavigationMode($nav);
if (xDiff > 0 && navigationPosition === "left") { // left swipe and left navigation
if (!isClosing) {
// TODO: trigger the action
}
isClosing = true;
} else if (xDiff < 0 && navigationPosition === "right") { // right swipe and right nawigation
if (!isClosing) {
// TODO: trigger the action
}
isClosing = true;
}
}
});
});
}
swipeToClose($(".nav"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment