LPChip
LPChip

Reputation: 884

Create link that only works outside of div

I have the following code:

<div class="popup">
    <div>
        Some content
    </div>
</div>
Some background html for the entire page

With the following CSS:

div.popup
{
    z-index:999;
    display:block;
    position:absolute;
    top:0px;
    left:0px;
    background-color: rgba(0,0,0,0.5);
    width:100vw;
    height:100vh;
    box-shadow: 0px 0px 0 200px rgba(0,0,0,0.5);

}

div.popup div
{
    background-color: #fff;
    margin: 20px;
    width: 320px;
    height: 200px;
}

My goal is to make it possible to click anywhere in the outer div to navigate to a different page. I tried it by encapsulating the outer div with a <a href="?" title="cancel"> tag, and tried an OnClick="alert(test);" on the outer div, part, but both of them will also trigger when the inner div is clicked.

I also tried to give the inner div a z-index of 9999 to make it pop out, but that didn't work either.

How can I make it so that I can click anywhere in the outer div to go to a page, whereas it won't happen if I click on the inner div?

Upvotes: 2

Views: 40

Answers (1)

nonopolarity
nonopolarity

Reputation: 150976

You need to stop the bubbling. The event will go from the child up to the container (and to the body, html, etc), and your container handler will be notified. To prevent that, tell the browser to stop the bubbling right at that point, using event.stopPropagation():

div.popup
{
    z-index:999;
    display:block;
    position:absolute;
    top:0px;
    left:0px;
    background-color: rgba(0,0,0,0.5);
    width:100vw;
    height:100vh;
    box-shadow: 0px 0px 0 200px rgba(0,0,0,0.5);

}

div.popup div
{
    background-color: #fff;
    margin: 20px;
    width: 320px;
    height: 200px;
}
<div class="popup" onclick="alert('will go to another page')">
    <div onclick="event.stopPropagation()">
        Some content
    </div>
</div>
Some background html for the entire page

Upvotes: 1

Related Questions