Dennis D
Dennis D

Reputation: 1343

Javascript/Jquery Single event target delegation

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.

Upvotes: 0

Views: 614

Answers (2)

desau
desau

Reputation: 3021

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)
}

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630379

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.

Upvotes: 3

Related Questions