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...
2 Answers 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.
2 Comments
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