Paul Paul - 1 month ago 12
jQuery Question

How to delegate each() in jQuery

It is possible to delegate .each() function in jquery? I want to bind my Div to li using delegate while using each(). Someone please help. Thanks in advance

I have this code

$('.calendar-container .item-list ul').each(function(){
$(this).slick({
slide: 'li',
slidesToShow: 3,
slidesToScroll: 3
});
});


I want something like this but its not working

$(document).delegate('.calendar-container .item-list ul','each',function(){
alert('dd')
$(this).slick({
slide: 'li',
slidesToShow: 3,
slidesToScroll: 3
});
});

Answer

No. You can't do this. Delegation in jQuery is for handling events that bubble up the parent chain. It appears you want to call .slick() on any newly created element that matches a selector. You can't do that with delegation since it doesn't fit the above definition of how it works and what it does. You aren't looking to handle an existing event that bubbles up the parent chain.

If you're looking for totally arbitrary monitoring of newly created objects or objects assigned matching classes, you'd probably have to use some sort of MutationObserver, though I suspect if we understood your entire situation, there's probably an easier and less generic way of solving your particular problem (like hooking into your code that modifies the DOM).

Comments