Question

I have a problem using jQuery.

I'm creating divs on the fly with javascript and this is the reason to use event bubbling to bind this divs with my jQuery functions. I'm using the tag body to start to find the divs with the productId attribute that I'm creating on the fly. The problem is that when click in one of the divs inside the div with the productId attribute don't run. Only in the part of the div that do not contain the other embedded divs. ¿Can someone help my? ;)

This is the code:

<div class="cartProduct" productId="2">
   <div class="names">Patatoes</div>
   <div class="units">5</div>
</div>

$('body').click(function(event) {
  if($(event.target).is('[productId]')) {
     ...
  }
}
Was it helpful?

Solution

Try this:

$('body').on('click','[productId]',function(event) {
   // do something
});

Demo: http://jsfiddle.net/L5jg8/

This uses the delegated form of the .on() method. When a click on the body occurs, jQuery will check if it was on an element that matches the selector in the second parameter. (If you're using an old version of jQuery you'll need to use .delegate() instead of .on(). If you're using a ludicrously old version try .live().)

Your existing code didn't work because event.target gives you the DOM element that initiated the event, i.e., the lowest-level child that you clicked on (which as you've found could be one of the children of the div you're trying to test for).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top