0

I have a site developed in PHp and jQuery. I have an image over another image in position absolute. Small image has event click and its parent have another event click. But when I click on the small image I don't want that the event of the parent is fired Example: enter image description here

If I click on the "ok" image the parent fire event click and i have two action, one from the "ok" image and another from the parent.

I have tried in this mode:

$(document).on('click','.social-like',function(event){
   //click on "ok" image
   event.preventDefault();
});
$(document).on('click','.block-shirt',function(){
  //click on rectangle
});

CSS:

.block-shirt{
    float:left;
    width:133px;
    height:170px;
}
.tee{
    position:absolute;
    top:0;
    left:15px;
    margin-top:5px;
    width:103px;
    z-index:5;
}
.social-like{
    position:absolute;
    bottom:10px;
    right:20px;
    z-index:10;
    width:24px;
    height:32px;
}

HTML:

<div class="block-shirt">
   <img src="rectangle.png" class="tee"/>
   <div class="social-like"></div>
</div>

6 Answers 6

3

Use

$('.block-shirt').click(function(e){
  if ($(e.target).is('.social-like'))
        return false; // do what you want
  else
        //.block-shirt clicked code

from : http://forum.jquery.com/topic/click-events-on-absolute-positioned-elements

http://api.jquery.com/event.target/

Sign up to request clarification or add additional context in comments.

Comments

2

You have to filter target:

$(document).on('click','.block-shirt',function(e){
    if($(e.target).is('.social-like')) return;
    //else do some stuff
});

Comments

1

You have to stop propagation of the event from child to parent

Try

event.stopPropagation()

for the child

1 Comment

doesn't works if using delegation because event is fired at delegate level
1

For this aim use event.stopPropagation().

Use event.preventDefault() if you don't want default action f.e. redirect on click on tag

Comments

1

Bind the event to the child directly not to the document

$('.social-like').on("click",function(e){e.stopPropagation()})

Comments

1

Please refer to this DEMO i just created.

in short i have used event.stopPropagation() to stop the bubbling of click event to its parent element. it will prevent any parent handlers from being executed.

also to prevent/cancel just default action, you should normally use event.preventDefault() rather then return false.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.