-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
56 lines (42 loc) · 1.12 KB
/
Copy pathmain.js
File metadata and controls
56 lines (42 loc) · 1.12 KB
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
const sidebar = document.getElementById('sidebar');
const toggleBtn = document.getElementById('toggle-btn');
if (sidebar && toggleBtn) {
const isMobile = () => window.matchMedia('(max-width: 768px)').matches;
const closeSidebar = () => {
sidebar.classList.remove('show');
};
toggleBtn.addEventListener('click', () => {
sidebar.classList.toggle('show');
});
// Close menu after choosing a section on mobile.
sidebar.querySelectorAll('a[href^="#"]').forEach((link) => {
link.addEventListener('click', () => {
if (isMobile()) {
closeSidebar();
}
});
});
// Close menu when tapping outside it on mobile.
document.addEventListener('click', (event) => {
if (!isMobile() || !sidebar.classList.contains('show')) {
return;
}
const target = event.target;
if (!(target instanceof Element)) {
return;
}
if (!sidebar.contains(target) && !toggleBtn.contains(target)) {
closeSidebar();
}
});
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
closeSidebar();
}
});
window.addEventListener('resize', () => {
if (!isMobile()) {
closeSidebar();
}
});
}