TheOrdinaryGeek
TheOrdinaryGeek

Reputation: 2323

Swiper.js Custom Pagination Name

Using swiper.js v4.0.6 I would like to display custom names on a pagination bar using the renderCustom API.

I need to display three slides, and their corresponding names which I have set using data- attributes in the HTML.

I have most of it working, but the item names aren't displaying in the correct order;

Here's a fiddle and code is below.

HTML

<div class="swiper-container">
  <div class="swiper-wrapper">
    <div class="swiper-slide" data-name="Item 1">
      <p>Testing 1</p>
    </div>
    <div class="swiper-slide" data-name="Item 2">
      <p>Testing 2</p>
    </div>
    <div class="swiper-slide" data-name="Item 3">
      <p>Testing 3</p>
    </div>
  </div>
  <div class="swiper-button-prev"></div>
  <div class="swiper-button-next"></div>
</div>
<div class="swiper-pagination"></div>

JS

var names = [];
$(".swiper-wrapper .swiper-slide").each(function(i) {
  names.push($(this).data("name"));
});
var swiper = new Swiper('.swiper-container', {
  pagination: {
    el: '.swiper-pagination',
    type: 'custom',
    renderCustom: function(swiper, current, total) {
      var text = "<span style='background-color:transperent;text-align: center;width:100%; display:block'>";
      for (let i = 1; i <= total; i++) {
        if (current == i) {
          text += "<span style='display:inline-block;border-top:3px solid red;text-align:left;margin-right:4px;width: 20%;color:red;padding:5px;'>" + names[i] + "</span>";
        } else {
          text += "<span style='display:inline-block;border-top:3px solid white;text-align:left; margin-right:4px;width: 20%;color:white;padding:5px;'>" + names[i] + "</span>";
        }
      }
      text += "</span>";
      return text;
    }
  },
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  }
});

I think the solution may be simple and I'm missing something in the loop, any help is appreciated.

Upvotes: 1

Views: 4657

Answers (1)

user2625636
user2625636

Reputation: 351

Swiper starts the loop (as many other languages) with 0, not one. So you have encountered a classic off-by-one error in your loop. Just use the following in your loop clause:

for (let i = 0; i <= total; i++) {

that should do the trick :)

Upvotes: 1

Related Questions