Search code examples
javascriptaddeventlistener

Sidebar not opening when clicked on a toggled. element


i'm currently working on a project where the user wants to be able to open the sidebar when the hamburger button on the header is not visible . To accomplish this task I made a button that only is shown when the header is out of view. The problem that is accruing is that the showSidebar function is not being executed. I also tried to put the functionality of the showSidebar directly in to the addEventListener as an anonymous function, with the same results.

The side bar is being closed whenever I click on anything that is not inside the sidebar or the hamburger button itself.

function showSidebar() {
    sidebar.classList.add('show');
    overlay.classList.add('enabled');
}

function togglePill() {
    const scrolled = window.scrollY;
    if (scrolled <= 69) {
        locationPill.classList.remove('show');
    } else if (scrolled > 69) {
        locationPill.classList.add('show');

        locationPill.addEventListener('click', showSidebar);
    }
}
window.addEventListener('scroll', togglePill);

Solution

  • make sure that the hide sidebar function is not toggled when you are clicking on the location pill

    document.addEventListener('click',
      e => !sidebar.contains(e.target)
           && e.target.parentElement !== hamburgerBtn
           && !e.target.classList.contains('location')
           && !e.target.parentElement.classList.contains('location') ?
                hideSidebar() : false
    );