Skip to content Skip to sidebar Skip to footer

Close Div With Click Outside (parent)

This is not a new problem on stackoverflow, but I've tried everything without success. I have a 'popup' created with two divs. The parent ist the background and the child is the po

Solution 1:

You should separate both events and attach the click to the window so you can detect the clicks outside of popup-content like :

let content = document.querySelector('.popup-content');
let popup = document.querySelector('.popup');
let button = document.querySelector('button');

button.onclick = () => {
  popup.style.display = 'block';
}

window.onclick = e => {
  if (e.target === popup) {
    popup.style.display = 'none';
  }
}
.popup {
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: rgb(0, 0, 0);
  background-color: rgba(0, 0, 0, 0.4);
  display: none;
}

.popup-content {
  background-color: #fff;
  margin: 10% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 25%;
  min-width: 470px;
  border-radius: 4px;
}
<button>
Open Popup
</button><divclass="popup"><divclass="popup-content"><h3>Popup Title</h3><p>Popup Text</p></div></div>

Solution 2:

you can try something like this :

instead of adding the EventListner to close the div on the button you need to add it on the document instead. and test on target if is not your button just like this :

let popup = document.querySelector('.popup');
    let button = document.querySelector('button');



    // Event that hide the popin if the click happen out popinfunctioncloseHandler(e) {
        if (e.target !== popup) {
            // We remove the event for better perfermanceremoveCloseListner();
            // We hide the popin
            popup.style.display = 'none';
        }
    }

    // Call this function when you open your popin popinfunctionaddCloseLitnerToDocument() {
        document.addEventListener("click", closeHandler);
    }

    functionremoveCloseListner() {
        document.removeEventListener("click", closeHandler)
    }

    // Add listner to Open Popin
    button.onclick = (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    // when popin is open// Add listner to the document// And show the popin
                    popup.style.display = 'block';
                    addCloseLitnerToDocument();
                }

Post a Comment for "Close Div With Click Outside (parent)"