Include navigation (arrows) and pagination (dots) on each slide itself in a slick slider

If you want to include navigation (arrows) and pagination (dots) on each slide itself in a slick slider, here's how you can achieve this:

1. HTML Structure

You need to place arrows and dots inside each slide so that they appear uniquely for each one.

Slide 1

Slide 2

Slide 3

2. Initialize Slick

Use Slick’s API to manage navigation and pagination for each slide:

$(document).ready(function () {
  $('.slider').slick({
    slidesToShow: 1,
    slidesToScroll: 1,
    infinite: true,
    speed: 500,
    arrows: false, // Disable global arrows
    dots: false, // Disable global dots
  });

  // Add custom controls for each slide
  $('.slider .slide').each(function (index, slide) {
    const $prevButton = $(slide).find('.prev');
    const $nextButton = $(slide).find('.next');

    // Go to the previous slide on click
    $prevButton.on('click', function () {
      $('.slider').slick('slickPrev');
    });

    // Go to the next slide on click
    $nextButton.on('click', function () {
      $('.slider').slick('slickNext');
    });

    // Generate custom dots for this slide
    const $dotsContainer = $(slide).find('.dots');
    const slideCount = $('.slider .slide').length;

    for (let i = 0; i < slideCount; i++) {
      const dot = $(``);
      dot.on('click', function () {
        $('.slider').slick('slickGoTo', $(this).data('slide'));
      });
      $dotsContainer.append(dot);
    }
  });

  // Sync active dots with slick events
  $('.slider').on('afterChange', function (event, slick, currentSlide) {
    $('.custom-dot').removeClass('active');
    $(`.custom-dot[data-slide="${currentSlide}"]`).addClass('active');
  });
});

3. CSS Styling

Make it visually appealing with CSS:

.slider {
  position: relative;
}

.slide {
  text-align: center;
  position: relative;
}

.controls {
  position: absolute;
  bottom: 20px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.controls .prev,
.controls .next {
  background-color: #007bff;
  color: #fff;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
}

.controls .prev:hover,
.controls .next:hover {
  background-color: #0056b3;
}

.controls .dots {
  display: flex;
  gap: 5px;
}

.controls .custom-dot {
  background-color: #ddd;
  border: none;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  cursor: pointer;
}

.controls .custom-dot.active {
  background-color: #007bff;
}

4. Final Outcome

  • Each slide now has its own arrows and pagination dots.
  • Clicking on these controls interacts seamlessly with the slick slider.
  • Dots update dynamically to reflect the current active slide.

No comments:

Post a Comment