-
Notifications
You must be signed in to change notification settings - Fork 0
/
menu.js
82 lines (73 loc) · 2.54 KB
/
menu.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const menuBtn = document.querySelector(".menu-btn");
const menuNav = document.querySelector(".menu");
const menuUl = menuNav.querySelector("ul");
let touchStartY = 0;
let touchMoveY = 0;
let savedTouchMoveY = 0;
let touchEndY = 0;
let touchStartX = 0;
let touchMoveX = 0;
let touchEndX = 0;
let isSwipeY = false;
const swipeThreshold = 50;
let isDesktop;
resize();
menuBtn.addEventListener("click", toggleMenu);
window.addEventListener("resize", resize);
function resize() {
isDesktop = window.innerWidth >= 900 ? true : false;
isDesktop && document.body.classList.remove("no-scroll");
if (!isDesktop && !menuNav.classList.contains("hidden")) document.body.classList.add("no-scroll");
}
const isTouchDevice = () => {
return window.matchMedia("(pointer: coarse)").matches;
}
menuNav.querySelectorAll("a").forEach(el => {
el.addEventListener("click", function () {
if (!menuNav.classList.contains("hidden")) {
toggleMenu();
}
})
});
function toggleMenu() {
if (isDesktop) return;
menuBtn.classList.toggle("isCross");
menuNav.classList.toggle("hidden");
document.body.classList.toggle("no-scroll");
if (isTouchDevice()) {
if (menuNav.classList.contains("hidden")) {
menuNav.removeEventListener("touchstart", menuSwipeStartX);
menuNav.removeEventListener("touchmove", menuSwipeMoveX);
menuNav.removeEventListener("touchend", menuSwipeEndX);
} else {
menuNav.addEventListener("touchstart", menuSwipeStartX, { passive: true });
menuNav.addEventListener("touchmove", menuSwipeMoveX);
menuNav.addEventListener("touchend", menuSwipeEndX);
}
}
}
function menuSwipeStartX(e) {
touchStartX = e.changedTouches[0].clientX;
}
function menuSwipeMoveX(e) {
touchMoveX = e.changedTouches[0].clientX;
if ((touchMoveX - touchStartX) < -swipeThreshold) {
menuNav.classList.add("isSwipingX");
let v = (touchMoveX - touchStartX + swipeThreshold) / window.innerWidth;
menuNav.style.transform = "translateX(" + v * 101 + "%)";
menuUl.style.opacity = 1 + v * 4;
}
}
function menuSwipeEndX(e) {
menuNav.classList.remove("isSwipingX");
touchEndX = e.changedTouches[0].clientX;
if ((touchEndX - touchStartX) < -swipeThreshold) {
menuNav.removeAttribute("style");
menuUl.removeAttribute("style");
toggleMenu(e);
} else {
menuNav.style.transform = "translateX(0%)";
menuNav.removeAttribute("style");
menuUl.removeAttribute("style");
}
}