Swiper nav buttons outside container

Gabriel Souza picture Gabriel Souza · Jan 22, 2018 · Viewed 12.4k times · Source

I'm trying to display the nav buttons outside the swiper container, because of the container overflow: hidden i had to create a wrap with position: relative and position the buttons absolutely.

That worked, the problem is that now the nav buttons control all sliders and i can't figure out a way to solve this.

I don't want to initialize multiple sliders with different classes if the slider is the same with different content.

JSFiddle

Answer

Vignesh Raja picture Vignesh Raja · Jan 22, 2018

Easy, tiny and tidy.

document.querySelectorAll('.swiper-container').forEach(function(elem) {
  new Swiper(elem, {
    slidesPerView: 2,
    spaceBetween: 10,
    navigation: {
      nextEl: elem.nextElementSibling.nextElementSibling,
      prevEl: elem.nextElementSibling,
    }
  });
});
body {
  padding: 20px 60px 40px;
}

.slider-produtos-wrap {
  position: relative;
  width: 100%;
  margin-top: 20px;
}

.swiper-slide {
  z-index: 1;
  height: 150px;
  background: blue;
}

.swiper-prev,
.swiper-next {
  width: 60px;
  height: 60px;
  background: red;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  border-radius: 60px;
  z-index: 9999;
}

.swiper-prev {
  left: -30px;
}

.swiper-next {
  right: -30px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.1.0/css/swiper.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.1.0/js/swiper.min.js"></script>
<div class="slider-produtos-wrap">
  <div class="slider-produtos-destaque swiper-container">
    <div class="swiper-wrapper">
      <div class="swiper-slide">Slide 1</div>
      <div class="swiper-slide">Slide 2</div>
      <div class="swiper-slide">Slide 3</div>
    </div>
  </div>

  <div class="swiper-prev"></div>
  <div class="swiper-next"></div>

</div>

<div class="slider-produtos-wrap">
  <div class="slider-produtos-destaque swiper-container">
    <div class="swiper-wrapper">
      <div class="swiper-slide">Slide 1</div>
      <div class="swiper-slide">Slide 2</div>
      <div class="swiper-slide">Slide 3</div>
    </div>
  </div>

  <div class="swiper-prev"></div>
  <div class="swiper-next"></div>

</div>