views:

27

answers:

3

Dear experts,

I realized event.target redundancy could cause a lot of problems in the future when they are binded with another event in the next level.

For example, when i have an Div element inside another.

<div id='div1'>
  <div id='div2>
  </div>
</div>

I use the follow Jquery code to bind an event.

$('div').bind('click', function(event){
   alert(event.target.id)
}

There are two alert boxes instead of one. I understand the concept of why is because there are 2 divs I am clicking.

Of course the problem in a deeper level is that when I am trying to bind an event after this event accordingly with the event.target, it binds x2 so on and so forth.

Is it possible to get rid of the event binding on the outside div and only capture the inside.

Thanks in advance.

+3  A: 

You can prevent the event from bubbling using event.stopPropgation() like this:

$('div').bind('click', function(event){
  alert(event.target.id);
  event.stopPropagation();
});

You can give it a try here. This will "trap" the click on the first <div> that gets it, and won't let it propagate up to any parents.

Nick Craver
A: 

call

event.stopPropagation()

to prevent the event from bubbling up.

By calling this method within your event handler, you effectivly prevent that parent nodes also get notice (and therefore) trigger the event (which is the default behavior).

jAndy
A: 

I think you just need to select the inside div in your bind call:

$('div:eq(0)').bind('click', function(event){
   alert(event.target.id)
}
desau