I have to following HTML:
-
...some more nesting
somel
Place another delegate handler on whatever contains the dynamically created elements, in this case the ul
, to stop the propagation.
$("ul.ulclass").delegate(".liclass div", "click", function(e) {
e.stopPropagation();
});
$("ul.ulclass").delegate(".liclass", "click", function(e) {
// main code for each li element
});
Because they're both delegate methods on the same element, the e.stopPropagation()
should work to prevent the handler even though the event has already bubbled up.
JSFIDDLE DEMO
Updated the demo to show it working with dynamic elements.
An alternative would be to simply bind handlers directly to your dynamically created div
elements.
So if you're using .load()
, I assume you're wiping out the old content and replacing it with new. In that case, in the callback, just select the divs, and rebind the handler.
$("ul.ulclass").load('/whatever/', function() {
// shortcut to binding a handler with stopPropagation and preventDefault
$(this).find('li.liclass div').bind('click', false);
});
If you're using latest version of jQuery, correct code would be:
$(document).on("click", ".liclass a", function(e) {
e.stopPropagation();
});
You need to call ".delegate" after each ajax request is completed in order for this to work.
Event delegation means: The event already bubbled to a "higher level" element. It is not possible to stop the propagation to this element any more (because it already happened). The propagation can only be stopped for elements even higher in the hierarchy. It will not work at all if you bound the delegate to "document" already.