0
  • all my elements are absolutely positioned
  • item2 is contained in item1
  • when I click on item2, the default behavior is to execute click of item2 and then click of item1
  • can I somehow prevent any action that was to be performed on item1 when I click on item2??

Please click on item2 in fiddle

My fiddle:

http://jsfiddle.net/z9Unk/59/

HTML

<div class="item1">
  item1
</div>
<div class="item2">
    item2
</div>
<div class="item3">
    item3
</div>

CSS:

item1 {
    position:absolute;
    width:150px;
    height:150px;
    background-color:red;
    top:5%;
}

.item3, .item2 {
    position:absolute;
    width:50px;
    height:50px;
    background-color:green;
    top:8%;
    left:1%;
    display:none;
}

.item3 {
    top:18%;
}

JS:

var item1 = $(".item1");
var item2 = $(".item2");
var item3 = $(".item3");

item1.hover(
    function() {
      item2.show();
      item3.show();
    },
    function() {
      item2.hide();
      item3.hide();
    }

);

item2.hover(
    function() {
      item3.hide();
    },
    function() {
    }

);

item2.click(
    function() {
        alert("Perform some function");
    }
);

item1.click(
    function() {
        alert("Perform item1 function");
    }
);
gaurav jain
  • 1,267
  • 8
  • 20
  • 36

2 Answers2

1

Simply return false:

item2.click(
    function() {
        alert("Perform some function");
        return false;
    }
);

item1.click(
    function() {
        alert("Perform item1 function");
        return false;
    }
);

Read this: What does "return false;" do?

Community
  • 1
  • 1
gdoron
  • 147,333
  • 58
  • 291
  • 367
1

you can prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

DOM Level 3 Events: stopPropagation

IE6-8 you can add return false in event handler or window.event.cancelBubble = true

if you use jquery, can use event.stopPropagation in all browser

anhulife
  • 566
  • 2
  • 7