Jacques Jacques - 3 months ago 19
jQuery Question

How to implement jQuery live() on jQuery code?

I have the following jQuery code:

$('.carousel[data-type="multi"].item').each(function(){
var next = $(this).next();
if (!next.length) {
next = $(this).siblings(':first');
}
next.children(':first-child').clone(true).appendTo($(this));

for (var i=0;i<2;i++) {
next=next.next();
if (!next.length) {
next = $(this).siblings(':first');
}

next.children(':first-child').clone(true).appendTo($(this));
}
});


As you can see, the code is cloning an element on carousel scroll.

The issue is that events on the element, a jQuery
.hide()
and
.show()
, is not being triggered because the clone is not cloning data events. I tried setting
clone(true)
but that does not work. It works before the clone happens (before scroll) but not after. Elsewhere I read that someone fixed a similar issue with
.live()
, but I have no idea of how to implement
.live()
here. Any jQuery / Javascript gurus?

Answer

AFAIK live is deprecated and you should instead use on.. .

According to the comments, it is not the hide() nor the show() commands that works, because the click event is not getting triggered on the dynamically added DOM elements.

To resolve this issue you can use on.

$('.carousel').on('click', '.item', function(e) {
    var $this = $(e.target); // should reference the `.item`

    //... perform the click event here for every item
});

Now the click event is attached to the element which contains the clickable items, so you can add and remove elements in the container and items with the classname item will trigger the event.

Comments