Scroll through items with buttons

by Stanly Pokrowsky

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-compat/3.0.0-alpha1/jquery.min.js"></script>
<div class="container">
  <div class="items">
    <div class="item">Товар 1</div>
    <div class="item">Товар 2</div>
    <div class="item">Товар 3</div>
    <div class="item">Товар 4</div>
    <div class="item">Товар 5</div>
    <div class="item">Товар 6</div>
    <div class="item">Товар 7</div>
    <div class="item">Товар 8</div>
    <!-- и так далее... -->
  </div>
</div>

<button class="prev" disabled>Prev</button>
<button class="next">Next</button>

CSS

.container {
  width: 100%; 
  overflow: hidden;
}

.items {
  display: flex;
  transition: transform 0.5s ease;
}

.item {
  width: 20%; /* Показать 5 товаров на экране */
  margin-right: 10px;
  flex-shrink: 0; /* Это важно, чтобы товары не сжимались */
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

JavaScript

$(document).ready(function() {
  let currentIndex = 0;
  const itemsToShow = 5;
  const $items = $('.items');
  const $allItems = $('.item');
  const totalItems = $allItems.length;

  // Функция для обновления сдвига
  function updateItemsPosition() {
    // Сдвигаем контейнер так, чтобы показывались только 5 товаров
    $items.css('transform', 'translateX(' + (-currentIndex * 20) + '%)');
    
    // Деактивируем/активируем кнопки
    if (currentIndex === 0) {
      $('.prev').prop('disabled', true);
    } else {
      $('.prev').prop('disabled', false);
    }

    if (currentIndex >= totalItems - itemsToShow) {
      $('.next').prop('disabled', true);
    } else {
      $('.next').prop('disabled', false);
    }
  }

  // Кнопка Prev
  $('.prev').click(function() {
    if (currentIndex > 0) {
      currentIndex--;
      updateItemsPosition();
    }
  });

  // Кнопка Next
  $('.next').click(function() {
    if (currentIndex < totalItems - itemsToShow) {
      currentIndex++;
      updateItemsPosition();
    }
  });

  // Инициализация состояния кнопок на старте
  updateItemsPosition();
});