0

I have two elements:

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

When I click a just alert a is coming, but when I click b I just want to see alert b.

I think this example explain me better.

http://jsbin.com/Aruciyi/1/edit?html,css,js,output

As on example how can I get just alert b by clicking red block...

bfavaretto
72k18 gold badges118 silver badges162 bronze badges
asked Sep 11, 2013 at 22:41
0

2 Answers 2

2

Use event.stopPropagation, like this:

function b(event){
 event = event || window.event;
 event.stopPropagation();
 alert('b');
}

This traps the click event in the inner div and keeps it from bubbling up to the outer div.

ALSO: change your onclick attribute like this:

<div class="b" onclick="b(event);">b</div>

So you are explicitly passing the event object to the b function.

answered Sep 11, 2013 at 22:45
Sign up to request clarification or add additional context in comments.

2 Comments

This does not work. I need to get alert b by clicking b (red) block.
@user2081672 Try now, I made a change.
0

The provided answers work, but I prefer to create one universal click function. I changed your classes to IDs so that getting them would be easier. Here's the code:

<div id="a" onclick="clickEvent(event, this);">a
 <div id="b" onclick="clickEvent(event, this);">b</div>
</div>

JavaScript:

function clickEvent(e, o) {
 alert(o.id);
 event = e || window.event;
 event.stopPropagation();
}

Here's a demo

answered Sep 11, 2013 at 23:08

1 Comment

the fuction did not work on IE I edited it as JavaScript: function b(){ try{ window.event.cancelBubble = true;} catch(err){} try{ event = event || window.event || e; event.stopPropagation();} catch(err){} alert('b'); } but now it not working on firefox

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.