Issue
I am trying to create a pop-up where the container is just a black background with some opacity, and then that div container contains the content of the popup.
Basically it looks something like:
<button (click)="showPopup = !showPopup">Open popup</button>
<div class="overlay-bg" (click)="showPopup = !showPopup" [ngClass]="showPopup ? 'is-active' : ''">
<div class="content">Some content</div>
</div>
The CSS looks something like:
.overlay {
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.5);
display: grid;
position: fixed;
pointer-events: none;
opacity: 0;
&.is-active {
opacity: 1;
pointer-events: all;
}
.content {
width: 400px;
height: 400px;
place-self: center;
background: red;
}
}
So basically, when the state is not active, it's not showing, and when is-active
is enabled by clicking the button, the overlay + content is displayed. Now, what I would also like is that when clicking the background, the pop-up should close - which is does. However, the problem is, that the pop-up also closes when I just click the content - which it shouldn't since it should be somewhat interactive.
So how do I prevent the pop-up from closing when interacting with the content div ?
Solution
Problem
The reason this happens is due to the event flow in javascript, which is the order in which events are handled. This is important when there are nested elements, like with your two divs ('overlay-bg' and 'content'). Modern browsers use event bubbling which means that the innermost child element handles the event first. The event then 'bubbles' and works its way outwards. In your case, the 'content' div must handle the event first. You do not want the pop-up to disappear when the 'content' div is clicked, but you do when the 'overlay-bg' div is clicked. Therefore you must find a way of stopping the event bubbling from occurring by capturing it with the onclick event on the 'content' div. This can be done by using the stopPropagation()
method of the event object.
Solution
To stop the event from bubbling upwards when the user clicks on the 'content' div, add an onclick event handler in the HTML:
<div class="content" onclick="preventBubbling(event)">Some content</div>
Then, with JavaScript, you can use the stopPropagation()
method of the event object which is passed as a parameter to the function. To achieve this, the function would look like this:
function preventBubbling(event) {
event.stopPropagation();
}
This stops the event from bubbling up to the parent div, so the click event is never triggered, and the pop-up does not hide (when the user clicks on the content div).
Answered By - goldenbanana42
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.