Home > Net >  Stop function on first or/and last item
Stop function on first or/and last item

Time:10-22

I have the following function:

// Go to the previous item
$(".owl-prev-custom").click(function () {
  $(".owl-carousel-timeline .item.item-year-active")
    .removeClass("item-year-active")
    .parent()
    .prev()
    .children()
    .addClass("item-year-active");

  var theHash = $(".owl-carousel-timeline .item.item-year-active").attr(
    "data-hash"
  );
});

With this html:

<div class="owl-carousel owl-carousel-timeline">
  <div class="owl-item">
    <div class="item" data-hash="2006">
      <div class="carousel-card"></div>
    </div>
  </div>
  <div class="owl-item">
    <div class="item" data-hash="2009">
      <div class="carousel-card"></div>
    </div>
  </div>
  <div class="owl-item">
    <div class="item" data-hash="2010">
      <div class="carousel-card"></div>
    </div>
  </div>
  <div class="owl-item">
    <div class="item" data-hash="2013">
      <div class="carousel-card"></div>
    </div>
  </div>
  <div class="owl-item">
    <div class="item item-year-active" data-hash="2013-2">
      <div class="carousel-card"></div>
    </div>
  </div>
</div>


<div class="owl-nav owl-nav-timeline">
  <div class="owl-prev-custom"></div>
  <div class="owl-next-custom"></div>
</div>

The problem I have is that the click event, when reaches the first item .owl-item:first (or last item .owl-item:last), does not stop and the class .item-year-active disappears since it goes to an item before the first owl-item. I would like to know how to stop my function in the first .owl-item and in the last .owl-item so that this does not happen.

Please let me know if I explain well, to give more details, English is not my primary language :)

CodePudding user response:

Check whether the active element is the first element, and skip it when you reach the end.

// Go to the previous item
$(".owl-prev-custom").click(function() {
  if (!$(".owl-carousel-timeline .item.item-year-active").is(".owl-carousel-timeline .item:first")) {
    $(".owl-carousel-timeline .item.item-year-active")
      .removeClass("item-year-active")
      .parent()
      .prev()
      .children()
      .addClass("item-year-active");
  }

  var theHash = $(".owl-carousel-timeline .item.item-year-active").attr(
    "data-hash"
  );
});
  • Related