Ad

Deleting Active (centered) Item In OwlCarousel

- 1 answer

I want the user to be able to delete the active/centered item in an OwlCarousel. The only piece of code I found w.r.t. deletion of items was this, so it seems to be a rather rare question:

$(".owl-carousel").trigger('remove.owl.carousel', [itm]).trigger('refresh.owl.carousel');

It works, but refers to the current item ID within the carousel, i.e. doesnt work anymore if I give numbers from my static HTML without reindexing. Here's a fiddle: https://jsfiddle.net/87x312wv/6

Is there any better way instead of counting the item-ID? I'm rather looking for something like - would be way more natural:

$(".owl-carousel").trigger('remove.owl.carousel', $('owl-carousel .active')).trigger('refresh.owl.carousel');

Any ideas?

Ad

Answer

I find a solution. For example, imagine that you want to remove each item by clicking on it:

html code:

<div class="owl-carousel owl-theme">
  <div class="item"><h4>1</h4></div>
  <div class="item"><h4>2</h4></div>
  <div class="item"><h4>3</h4></div>
  <div class="item"><h4>4</h4></div>
  <div class="item"><h4>5</h4></div>
  <div class="item"><h4>6</h4></div>
  <div class="item"><h4>7</h4></div>
  <div class="item"><h4>8</h4></div>
  <div class="item"><h4>9</h4></div>
  <div class="item"><h4>10</h4></div>
  <div class="item"><h4>11</h4></div>
  <div class="item"><h4>12</h4></div>
</div>

js code:

  $(".owl-item").on("click", function (event) {
    var items = $(".owl-item");
    items.each((index, item) => {
      if (item.isEqualNode(event.currentTarget)) {
        $(".owl-carousel")
          .trigger("remove.owl.carousel", index)
          .trigger("refresh.owl.carousel");
        return;
      }
    });
  });
Ad
source: stackoverflow.com
Ad