0

I'm trying to build a (semi-transparent) overlay that covers all on a web page. Similar to this: http://www.jankoatwarpspeed.com/use-jquery-to-turn-off-the-lights-while-watching-videos

<div id="overlaySplash" onclick="clickHandler(this)">
    <div id="insideBox">
   [ label elements here with onclick="dosomething()" ]
    </div>
</div>

css

#overlaySplash {
    position: absolute;
    top: 0;
    left: 0;
    bottom:0;
    right:0;
    background: rgb(50, 50, 50);
    background: rgba(0, 0, 0, .50);
    z-index: 50;
}
#insidebox {
    position: absolute;
    z-index: 100;
    left: 15%;
    right: 15%;
    bottom: 5%;
    line-height: 50px;
    text-align: left;
}

The problem is that I'm not using jquery and the overlay div will have some clicable contents on int. I have this function below but when I click on elements inside the main overlay div JS will return e.id as being the overlay div itself, not the clicked element. This way I can't tell where the user really clicked.

function clickHandler(e){ //hide the div overlaySplash

  e = e || event; 

  alert(e.id);
}

THE BOTTOM LINE:
user clicked an label inside the div: dosomething();
user clicked the background (the DIV itself): closeOverlaySplash();

2 Answers2

2

I don't think you need to completely stop propagation as it may serve some purpose later on. It might be easiest to create a separate js & css files that encompass this functionality for ease of use.

The issue you have is basically the event is bubbling up to the parent when it isn't currently needed. You can easily check the event.target.id to see if the parent was clicked or not. With this you can make sure the overlay was clicked vs the content.

eg:

if (event.target.id == "overlay") { 
    //hide the overlay 
}

JSFiddler

Justin
  • 3,337
  • 3
  • 16
  • 27
1

Like this:

HTML

<div id="overlaySplash" onclick="clickHandler(event);">
    <div id="insideBox" onclick="clickHandlerInner(event);">Inner</div>
</div>

JS

function clickHandler(event) {
    alert("no");
}
function clickHandlerInner(event) {
    if (!event) var event = window.event;
    event.cancelBubble = true; //IE
    if (event.stopPropagation) event.stopPropagation()
    alert("yes")
}

jsFiddle

Balint Bako
  • 2,500
  • 1
  • 14
  • 13