Question

I have the following div structure:-

<div id="a" onclick="function1();">
<div id="b">
</div>

<div id="c">
</div>
</div>

Of course, clicking "a" will trigger function1() since "b" and "c" are located inside "a", when click on "b" or "c", function1() is also triggered.

Actually, I don't want function1() to be triggered when clicking "b". I tried to use z-index to make "b" very above "a", but it doesn't help.

I am seeking a way that is similar to:-

 <div id="b" onclick="function1() return false"></div>
Was it helpful?

Solution 2

You have to look at the event's target.

With your HTML:

<div class="a">
  <div class="b">Hello</div>
  <div class="c">World</div>
</div>

You can use this Javascript (jQuery):

$('.a').on('click', function(event){
  var $target = $(event.target);
  if($target.is('.a')){
    alert('You actually clicked .a');
  } else {
    alert('You did not click .a');
  }
});

Here's a quick demo with jQuery.

http://jsbin.com/ijinuz/1/edit

OTHER TIPS

Simply:

$('#a').children().on('click', function(event) {
   event.stopPropagation();
});

Here you have a demo Fiddle.


You could possibly do this by passing event in the function set to onclick, and checking if the event.target.id !== "b":

<!DOCTYPE html>
<html>
    <head>
        <title>asdf</title>
    </head>
    <body>
        <div id = "a" onclick = "doSomething(event);">
            div "a"
            <div id = "b">
                div "b"
            </div>
            <div id = "c">
                div "c"
            </div>
        </div>


        <script type = "text/javascript">
            function doSomething(e) {
                            if (e.target.id !== "b") {
                                alert(e.target.id);
                            }
            }
        </script>
    </body>
</html>


Here is the jsfiddle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top