| 1 |
import debounce from 'lodash.debounce'; |
| 2 |
|
| 3 |
const menu = document.querySelector('.age-gate-toolbar'); |
| 4 |
const HIDDEN_CLASS = 'age-gate-toolbar__extra--hidden' |
| 5 |
const BUTTON_HIDDEN_CLASS = 'age-gate-toolbar__button--hidden'; |
| 6 |
|
| 7 |
if (menu) { |
| 8 |
const button = menu.querySelector('.age-gate-toolbar__button'); |
| 9 |
const links = menu.querySelector('.age-gate-toolbar__tabs'); |
| 10 |
const extra = menu.querySelector('.age-gate-toolbar__extra'); |
| 11 |
const title = menu.querySelector('.age-gate-toolbar__title'); |
| 12 |
|
| 13 |
let numOfItems = 0; |
| 14 |
let totalSpace = 0; |
| 15 |
const breakWidths = []; |
| 16 |
|
| 17 |
Array.from(links.children).forEach((item) => { |
| 18 |
totalSpace = totalSpace + (item.clientWidth + 10); |
| 19 |
numOfItems += 1; |
| 20 |
breakWidths.push(totalSpace); |
| 21 |
}); |
| 22 |
|
| 23 |
// console.log(numOfItems, totalSpace, breakWidths); |
| 24 |
|
| 25 |
let availableSpace, numOfVisibleItems, requiredSpace; |
| 26 |
|
| 27 |
const check = () => { |
| 28 |
|
| 29 |
availableSpace = menu.clientWidth - (title.clientWidth + 10) - 20 - button.clientWidth; |
| 30 |
console.log(availableSpace); |
| 31 |
console.log(breakWidths); |
| 32 |
|
| 33 |
numOfVisibleItems = links.children.length; |
| 34 |
requiredSpace = links.clientWidth + (title.clientWidth + 10) + 20; |
| 35 |
|
| 36 |
console.log(requiredSpace > breakWidths[numOfVisibleItems - 1], requiredSpace, breakWidths[numOfVisibleItems - 1]); |
| 37 |
if (requiredSpace > breakWidths[numOfVisibleItems - 1] && links.children.length) { |
| 38 |
const eat = Array.from(links.children)[links.children.length - 1]; |
| 39 |
|
| 40 |
if (eat) { |
| 41 |
extra.insertAdjacentElement('afterbegin', eat); |
| 42 |
} |
| 43 |
numOfVisibleItems -= 1; |
| 44 |
|
| 45 |
check(); |
| 46 |
} else if (availableSpace > requiredSpace && extra.children.length) { |
| 47 |
const spit = Array.from(extra.children)[0]; |
| 48 |
|
| 49 |
if (spit) { |
| 50 |
links.insertAdjacentElement('beforeend', spit); |
| 51 |
} |
| 52 |
numOfVisibleItems += 1; |
| 53 |
} |
| 54 |
|
| 55 |
button.dataset.count = numOfItems - numOfVisibleItems; |
| 56 |
|
| 57 |
if (numOfVisibleItems === numOfItems) { |
| 58 |
button.classList.add(BUTTON_HIDDEN_CLASS); |
| 59 |
} else { |
| 60 |
button.classList.remove(BUTTON_HIDDEN_CLASS); |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
window.addEventListener('resize', debounce(check, 100)); |
| 65 |
|
| 66 |
button.addEventListener('click', e => extra.classList.toggle(HIDDEN_CLASS)); |
| 67 |
|
| 68 |
window.addEventListener('DOMContentLoaded', check); |
| 69 |
} |
| 70 |
|