Why prepend does trigger once in a loop?

57 views Asked by At

I'm not very good at Javascript, I am trying to make an auto collapsing on overflow menu using Vanilla Js.
I'm happy with what I've managed to do so far. But I have a problem with ```appendChild``` / ```prepend```, they are triggered only once in my loop. When I refresh the page every overflowed link has gone under the more menu, but As I resize (decrease) the window,overflowed links still goes under the more menu, but the more menu itself isn't updating.
function collapseMenu() {
let menu = document.querySelector(".menu");
let menuChildren = menu.querySelectorAll('li');
let i = menuChildren.length - 1;

let other = document.createElement("li");
other.setAttribute("onclick", "submenu(this)");
other.id = 'other';
other.innerHTML = 'More';

let submenu = document.createElement("ul");
submenu.classList.add('submenu', 'hidden');
other.appendChild(submenu);

if (menu.offsetWidth >= window.innerWidth) {
    let drop;
    if (!menu.contains(document.getElementById('other'))) {
        menu.appendChild(other);
    }
    while (menu.offsetWidth >= window.innerWidth) {
        drop = menu.removeChild(menuChildren[i]);
        submenu.prepend(drop);
        i--;
    }

} else {
    //On increase window
}

}

collapseMenu();
window.addEventListener('resize', collapseMenu);

Please help, thanks

0

There are 0 answers