2

Simple problem with what seems to be an incredibly difficult solution.

I have a DIV wrapper with a z-index that is lower than a DIV that is inside the wrapper. (basically a background with a DIV on top of it)

When I run the console.log() on the wrapper, and the DIV, I notice that when I click on the wrapper it only logs the click for the wrapper.

But when I click on the DIV inside the wrapper, it logs clicks for both the wrapper and the DIV at the same time.

How the heck do I set this up so that when I click on the DIV inside the wrapper, it will only register a click for that DIV and not the wrapper as well??

Alex
  • 1,112
  • 4
  • 16
  • 30

2 Answers2

2

You'll want to use stopPropagation. See this for more info:

event.preventDefault() vs. return false

Community
  • 1
  • 1
Jeff
  • 2,778
  • 6
  • 23
  • 27
2

Expanding on Jeff's answer, here's some basic sample code:

<style type="text/css">
    div {width:100px;height:100px;}
    #parent {padding:50px;background-color:black}
    #child {background-color:yellow}
</style>

<script type="text/javascript">
    $(function () {
        $('div').click(function (event) {
            if ($(this).parents('div')) {
                event.stopPropagation();
            }
            console.log($(this).attr('id'));
        });
    });
</script>

<div id="parent">
    <div id="child"></div>
</div>
ataddeini
  • 4,931
  • 26
  • 34
  • While this solution does solve the issue, it kills all clicks on on my wrapper DIV. Basically I want only the child DIV to register the click for that DIV when you click on it, and only want the parent DIV to register a click when I click on the parent. This solution kills click recognition of the wrapper DIV Thoughts? – Alex Apr 22 '11 at 13:08
  • 1
    Nevermind, I figured it out. I had it in the wrong place. THANKS AGAIN FOR YOU HELP! MUCH APPRECIATED! – Alex Apr 22 '11 at 13:10
  • @Alex: Yeah, you will definitely want to narrow down your selectors. It's almost never a good idea to use `div` as a selector, but for this basic scenario it seemed relevant. – ataddeini Apr 22 '11 at 13:27