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
const header = document.querySelector('header#main');
const navItems = document.querySelectorAll('.nav-item');
function positionDropdown(item) {
const dropdown = item.querySelector('.nav-dropdown');
if (!header || !dropdown) return;
dropdown.style.setProperty('--dropdown-shift', '0px');
requestAnimationFrame(() => {
const headerRect = header.getBoundingClientRect();
const dropdownRect = dropdown.getBoundingClientRect();
let shift = 0;
if (dropdownRect.right > headerRect.right) {
shift = headerRect.right - dropdownRect.right;
}
if (dropdownRect.left + shift < headerRect.left) {
shift = headerRect.left - dropdownRect.left;
}
dropdown.style.setProperty('--dropdown-shift', `${shift}px`);
});
}
navItems.forEach((item) => {
item.addEventListener('mouseenter', () => positionDropdown(item));
item.addEventListener('focusin', () => positionDropdown(item));
});
window.addEventListener('resize', () => {
document.querySelectorAll('.nav-item:hover, .nav-item:focus-within').forEach(positionDropdown);
});