Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent events firing for overlapping HTML elements

So, I've got two elements, one nested within the other

<div id="outer">
    <div id="inner">
         <p>Lorem Ipsum</p>
    </div>
</div>

The outer container is larger than the inner, effecting a modal overlay layout. I want to register a click event on the exposed surface of the outer that will cause both to be dismissed, but I do not want this to occur if you click on the inner div.

I'm using jQuery delegate/stopPropagation, and trying to interrogate the element to ensure it's the outer div, but to no avail - it still recieves the outer event. I'm considering hand cranking in a hit area outside the inner div, but I want to know if there's a more elegant alternative.

EDIT:

several good solutions posted here - many thanks for feedback!

like image 712
sunwukung Avatar asked Jan 04 '13 17:01

sunwukung


People also ask

Why are my elements overlapping HTML?

This could happen for several reasons, especially when you consider the position problems with divs from one website to another. Similarly, box elements may overlap for a few reasons, ranging from positioning errors to overflow issues and simple float problems.

Can HTML elements overlap?

CSS z-index is one of the most important elements, and through it, HTML elements can be overlapped with different depths. In practice, z-index refers to the layout of a web page (if you lay one layer over another, then the layer the bottom layer will be hidden from the top layer.)

Which position values can be used to make overlapping elements without overflowing content?

position: absolute; Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.


2 Answers

$("#inner").click(function(event){
  event.stopPropagation();
  // do something
});  

here's a fiddle: http://jsfiddle.net/sajjansarkar/fA2sd/1/

like image 52
Sajjan Sarkar Avatar answered Sep 17 '22 15:09

Sajjan Sarkar


$('#outer').on('click', function (e) {
    if ( e.target != this) return;
    // run your code here...
});

Here's the fiddle: http://jsfiddle.net/9sLCx/

like image 38
Joseph Silber Avatar answered Sep 17 '22 15:09

Joseph Silber