1

I'm puzzled by something, thought someone here might have insight.

I've built a simple overlay, but it's not working as expected. Here's the css:

    #overlayOuter {
        display: none;
        position: absolute;
        height: 100%;
        width: 100%;
        background: #000;
        z-index: 100;
        }
    #overlayInner {
        position: absolute;
        top: 100px;
        left: 200px;
        width: 600px;
        height: 400px;
        z-index: 101;
        }

The html is simple:

    Blahblahblah!
    <a href="#" onclick="$('#overlayOuter').show();return false;">show overlay</a>
    <div id="overlayOuter">
        <div id="overlayInner">
            Oyeah? Blahblah!
        </div>
    </div>

I then wanted jquery to close the overlay when someone clicked on overlayOuter but not the overlayInner box (so I could include forms and such).

The first jquery I was expecting to work was ...

    $('#overlayOuter').click(function() {
        $('#overlayOuter').fadeOut('fast');
    });

... which works but strangely also closes when clicking overlayInner! Any forms, etc. are now useless!

The following does work as desired ...

    $('#overlayOuter').click(function(e) {
        if ($(e.target).parents('#overlayInner').length==0) {
            $('#overlayOuter').fadeOut('fast');
        }
    });

... but WTF!! Shouldn't the first one work? Isn't the z-index enough to mask overlayInner separate from overlayOuter?

designosis
  • 5,182
  • 1
  • 38
  • 57

4 Answers4

2

You're nesting the elements, so when you click the inner div, you're still clicking the outer.

you need to separate them like this:

<div id="overlayOuter">
</div>
<div id="overlayInner">
</div>

Not a problem with layout here that way, since you did set the position to absolute anyway

Here's the updated jfiddle from Stack 101s initially built one http://jsfiddle.net/Dapuc/3/

Semyazas
  • 2,101
  • 14
  • 14
1

This is due to Javascript event propagation/bubbling. Events that take place on an element will also take place on the elements containers. To avoid this, check that event.target is the element you want, like in this demo: http://jsfiddle.net/WQS3V/

arnemart
  • 14,180
  • 3
  • 17
  • 11
0

The first one does work :

http://jsfiddle.net/Dapuc/1/

Sparkup
  • 3,686
  • 2
  • 36
  • 50
0

You can add this:

$('#overlayInner').click(function(e) {
  e.stopImmediatePropagation();
});