Search code examples
javascriptjqueryowl-carouselowl-carousel-2

Owl Carousel 2 remove specific item


I use Owl Carousel 2 and my HTML code is as following. Each image will have a small "x" icon at the upper right corner, when clicked I want the image to be removed from the carousel.

When clicking on the first time, it works well, because the index passed to the "remove_image" function is correct. But on a second click on another image, the index will not be correct anymore.

For example: 1st click on image2.jpg, the index passed to "remove_image" is 1, this is correct. Image properly removed from Owl Carousel 2.

2nd click on image4.jpg, the index passed to "remove_image" is 3. this index is wrong. This is because Owl Carousel 2 has been updated after the image2 was removed. The correct index for image4.jpg now is 2.

How can I fix this problem? Please help. Thanks.

<div class="owl-carousel owl-theme">
    <div class="item"><img src="/image1.jpg" /><a onclick="remove_image(0);"><i class="icon-remove"></i></a></div>
    <div class="item"><img src="/image2.jpg" /><a onclick="remove_image(1);"><i class="icon-remove"></i></a></div>
    <div class="item"><img src="/image3.jpg" /><a onclick="remove_image(2);"><i class="icon-remove"></i></a></div>
    <div class="item"><img src="/image4.jpg" /><a onclick="remove_image(3);"><i class="icon-remove"></i></a></div>
    <div class="item"><img src="/image5.jpg" /><a onclick="remove_image(4);"><i class="icon-remove"></i></a></div>
    <div class="item"><img src="/image6.jpg" /><a onclick="remove_image(5);"><i class="icon-remove"></i></a></div>
</div>
function remove_image(index) {
    $('.owl-carousel').owlCarousel('remove', index).owlCarousel('update');
}

Solution

  • You use fixed indexes in your calls to remove_image. Since these aren't updated as items are removed, those fixed indexes become inaccurate.

    A quick (but not necessarily the best) fix would be to use this, instead of fixed indexes, to pass in the anchor elements themselves and then have your function derive the target index from that:

    <div class="owl-carousel owl-theme">
        <div class="item"><img src="/image1.jpg" /><a onclick="remove_image(this);"><i class="icon-remove"></i></a></div>
        <!-- more slides -->
    </div>
    
    function remove_image(trigger) {
        var $item = $(trigger).closest('.owl-item');
        var index = $item.closest('.owl-stage').children().index($item);
        $item.closest('.owl-carousel').owlCarousel('remove', index).owlCarousel('update');
    }
    

    .owl-stage and .owl-item are some of several elements that are added when owl carousel is initialized. .owl-stage sits between the user-provided container and items, wrapping those items. .owl-item wraps each item and are children of .owl-stage.

    References: