Skip to content
Advertisement

Hide div with window.addEventListener doesn’t work

I’ve created some kind of notification div which contains notifications, it shows when user clicks on notification icon and I wanted to do something like if the user clicks somewhere where isn’t part of this notification container the container will hide, with dropdown menu it works but with this div it isn’t and I have no idea why… Someone could help? Someone have any idea what am I doing wrong?

This is container HTML:

<div class="notifications-container">
    <div class="notifications-container-top-bar">
        <span>Notyfications</span>
        <div class="btns">
           <div class="seenAll">
                <img src="static/img/icons/checkedIcon.svg" alt="Seen all btn">
           </div>
            <div class="closeNotifications">
              <img src="static/img/icons/menu/close.svg" alt="Close">
            </div>
        </div>
    </div>
    <div class="noNotif">
         <p>No new notifications</p>
    </div>
    <div class="notifications-container-list">
        // notification items here
    </div>
    <div class="notifications-container-bottom-bar">
         <p id="loadMoreNotif">See more</p>
    </div>
</div>

Default css for this container is display: none; and after user click on notifications icon its gets active class which contains display: block;

I need to remove the active class when user clicks somewhere where is not a part of notifications container, this is how my js looks like

const notifContainer = document.getElementsByClassName("notifications-container")[0];

  openNotif.addEventListener("click", ()=>{ //it works
    notifContainer.classList.add("active");
  });

window.addEventListener('click', function(e) {
        if (!notifContainer.contains(e.target)) {
            notifContainer.classList.remove('active');
        }
});

It doesn’t work, after I added the window event listener the container won’t open anymore. Any ideas?

Advertisement

Answer

Your window click event is fired when you click openNotif, so what is going on is that the active class is being added and then removed. In the function removing the attribute you should check that event.target is not the element or selector firing the “show” action.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement