0

I have a custom class called masked on the body tag. In the middle of the page, I have a DIV with about 50% width and height of the page.

I am trying to attach a click handler only to the body.masked selector, but the problem is that whenever the inner DIV is clicked, the click handler on that body.masked selector is also fired.

As if the DIV in the middle is "transparent". How do I avoid that?

Here's some code:

$('body.masked').click(function(){
  alert();
})

And HTML:

<body class="masked">
  <div style="width:50%;height:50%;text-align:center;>Lorem ipsum</div>
</div>
Dzhuneyt
  • 8,437
  • 14
  • 64
  • 118

1 Answers1

2

It is because of event bubbling.

It makes an event happened in a child element to bubble to the top of the event tree. That is why it is happening.

In the event handler you can check the e.target value to check where there event had occured.

ex:

$('.top').on('click', function(e){
    console.log(e, e.currentTarget, e.target, this);
    if($(e.target).is(this)){
        console.log('proceed')
    }
})

Fiddle

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Also, for future readers, this answer might be of some help: http://stackoverflow.com/questions/11545518/hide-a-div-when-clicked-outside-of-it?rq=1 – Dzhuneyt Jan 22 '13 at 14:13