0

I am trying to exit the popup card by clicking anywhere other than the card i.e. on the blurred background, but I am not able to add the EventListener to the div, because the class is toggled off and the error is Cannot read property 'addEventListener' of null at... This code doesn't work.

const blurMe = document.querySelector(".blur");
blurMe.addEventListener("click", function () {
        for (let index = 0; index < 3; index++) {
            card[index].classList.add("hidden");
        }
        blurMe.classList.remove("blur");
 }); 

My cross button is working fine but I don't know how to add the feature to exit the popup just by clicking anywhere else on the screen. https://codepen.io/rhythmshandlya/pen/wvgMwyz please add the code to

  • 1
    why not use a delegated event handler assigned to the body and react according to which element is clicked – Professor Abronsius Mar 25 '21 at 16:16
  • Use [event delegation](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead. See [the tag info](https://stackoverflow.com/tags/event-delegation/info) and [What is DOM Event delegation?](/q/1687296/4642212). For example, bind the listener to the `
    ` and check inside the event if `this.matches(".blur")`. Alternatively, bind an event globally and check if the event argument’s [`target`](https://developer.mozilla.org/en-US/docs/Web/API/Event/target) matches the `
    ` or not; add more logic to determine if the popup is hidden or not, etc.
    – Sebastian Simon Mar 25 '21 at 16:16

0 Answers0