Jason Ryan
Jason Ryan

Reputation: 41

Simple jQuery Carousel Slide Counter

I have a simple text-based horizontal slider within a section of my website that scrolls left and right which is controlled by mouse scroll. I am trying to figure out how to show the current index of the slides and the total number of slides. e.g. 1/4 - and update the current index as you scroll through slides.

jQuery(function($) {
  var slideContainer = $('.inner-slide-container');
  var totalSlides = slideContainer.children().length;
  var firstSlide = slideContainer.index() + 1;

  $('.slide-num').html('<span class="slide-index">' + firstSlide + '</span>' + '/' + '<span class="slide-total">' + totalSlides + '</span>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slider-container">
  <div class="inner-slide-container">
    <div id="slide1" class="slide active">
      <h3>This is Slide 1</h3>

      <p>Some content for slide 1</p>
    </div>

    <div id="slide2" class="slide">
      <h3>This is Slide 2</h3>

      <p>Some content for slide 2</p>
    </div>

    <div id="slide3" class="slide">
      <h3>This is Slide 3</h3>

      <p>Some content for slide 3</p>
    </div>

    <div id="slide4" class="slide">
      <h3>This is Slide 4</h3>

      <p>Some content for slide 4</p>
    </div>
  </div>
  <div class="slide-num"></div>
</div>

The first slide gets the class "active", then as a user scrolls, it switches the "active" class to the next slide and then reverses when scrolling back the other way.

I am lost as to where to begin with this, I have looked at using $.each, and a 'for' loop but can't figure it out what the best approach is to updating the "current index" as you scroll through.

Not much of a JS guy but thought I could give it a shot and it has proven to be a little harder then it seems.

Any inisght or a push in the right direction would be greatly appreciated.

Upvotes: 2

Views: 1907

Answers (4)

Murali Nepalli
Murali Nepalli

Reputation: 1618

The easiest way would be, handle any sliding event, check which "slide" element has the class "active" and find it's index.

Pseudo code

function slidehandler () { // Make sure following code runs when slide changes
   console.log( "current index - " + $(".slide.active").index() );
   console.log( "Total slides - " + $(".slide").length );
}

Upvotes: 0

Marios Nikolaou
Marios Nikolaou

Reputation: 1336

Check my answer, i have added comments to understand better.

        //add all slides elements in array
        let slidesArr = $('.slide');
        //console.log(slidesArr);
        //console.log(slidesArr.length);
        
        //check before scroll for .slide that has active class
        //and show it to the user
        $.each(slidesArr, function(index, item) {
            if( $(item).hasClass('active')){
                $('.slide-num').html("<span>Slider no."+ (index+1) +"/"+slidesArr.length+" slide:"+item.id+"</span>");
            }
        });

       //scroll event
        $(window).scroll(function(){
            let scrolling = $(this);
            $.each(slidesArr, function(index, item) {
                let currentIndex = index + 1;
                
                //find each slide using offsetTop value
                //if the scrolling value is greater than the current slide offsetTop value select it as active
                if(scrolling.scrollTop() >= item.offsetTop){
                    //remove active class from all siblings
                    $(item).siblings().removeClass('active');
                    //add active class to the current slide
                    $(item).addClass('active');
                }

                if($(item).hasClass('active')){
                    $('.slide-num').html("<span>Slider no."+currentIndex+"/"+slidesArr.length+" slide:"+item.id+"</span>");
                }
            });

        });
body{height:1000px; }
 .slide-num{ position: fixed; top:50px;right:100px;border:1px solid red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slide-container">
        <div id="slide1" class="slide active">
          <h3>This is Slide 1</h3>
      
          <p>Some content for slide 1</p>
        </div>
      
        <div id="slide2" class="slide">
          <h3>This is Slide 2</h3>
      
          <p>Some content for slide 2</p>
        </div>
      
        <div id="slide3" class="slide">
          <h3>This is Slide 3</h3>
      
          <p>Some content for slide 3</p>
        </div>
      
        <div id="slide4" class="slide">
          <h3>This is Slide 4</h3>
      
          <p>Some content for slide 4</p>
        </div>

        <div class="slide-num"></div>
      </div>

Upvotes: 0

Swift
Swift

Reputation: 820

// this is simple slideshow with js     
<!DOCTYPE html>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
    * {box-sizing: border-box}
    body {font-family: Verdana, sans-serif; margin:0}
    .mySlides {display: none}
    img {vertical-align: middle;}

    /* Slideshow container */
    .slideshow-container {
      max-width: 1000px;
      position: relative;
      margin: auto;
    }

    /* Next & previous buttons */
    .prev, .next {
      cursor: pointer;
      position: absolute;
      top: 50%;
      width: auto;
      padding: 16px;
      margin-top: -22px;
      color: white;
      font-weight: bold;
      font-size: 18px;
      transition: 0.6s ease;
      border-radius: 0 3px 3px 0;
      user-select: none;
    }

    /* Position the "next button" to the right */
    .next {
      right: 0;
      border-radius: 3px 0 0 3px;
    }

    /* On hover, add a black background color with a little bit see-through */
    .prev:hover, .next:hover {
      background-color: rgba(0,0,0,0.8);
    }

    /* Caption text */
    .text {
      color: #f2f2f2;
      font-size: 15px;
      padding: 8px 12px;
      position: absolute;
      bottom: 8px;
      width: 100%;
      text-align: center;
    }

    /* Number text (1/3 etc) */
    .numbertext {
      color: #f2f2f2;
      font-size: 12px;
      padding: 8px 12px;
      position: absolute;
      top: 0;
    }

    /* The dots/bullets/indicators */
    .dot {
      cursor: pointer;
      height: 15px;
      width: 15px;
      margin: 0 2px;
      background-color: #bbb;
      border-radius: 50%;
      display: inline-block;
      transition: background-color 0.6s ease;
    }

    .active, .dot:hover {
      background-color: #717171;
    }

    /* Fading animation */
    .fade {
      -webkit-animation-name: fade;
      -webkit-animation-duration: 1.5s;
      animation-name: fade;
      animation-duration: 1.5s;
    }

    @-webkit-keyframes fade {
      from {opacity: .4} 
      to {opacity: 1}
    }

    @keyframes fade {
      from {opacity: .4} 
      to {opacity: 1}
    }

    /* On smaller screens, decrease text size */
    @media only screen and (max-width: 300px) {
      .prev, .next,.text {font-size: 11px}
    }
    </style>
    </head>
    <body>

    <div class="slideshow-container">

    <div class="mySlides fade">
      <div class="numbertext">1 / 3</div>
      <img src="https://www.w3schools.com/howto/img_nature_wide.jpg" style="width:100%">
      <div class="text">Caption Text</div>
    </div>

    <div class="mySlides fade">
      <div class="numbertext">2 / 3</div>
      <img src="https://www.w3schools.com/howto/img_snow_wide.jpg" style="width:100%">
      <div class="text">Caption Two</div>
    </div>

    <div class="mySlides fade">
      <div class="numbertext">3 / 3</div>
      <img src="https://www.w3schools.com/howto/img_snow_wide.jpg" style="width:100%">
      <div class="text">Caption Three</div>
    </div>
    </div>
    <br>

    <div style="text-align:center">
      <span class="dot" onclick="currentSlide(1)"></span> 
      <span class="dot" onclick="currentSlide(2)"></span> 
      <span class="dot" onclick="currentSlide(3)"></span> 
    </div>

    <script>
    var slideIndex = 1;
    showSlides(slideIndex);

    function plusSlides(n) {
      showSlides(slideIndex += n);
    }

    function currentSlide(n) {
      showSlides(slideIndex = n);
    }

    function showSlides(n) {
      var i;
      var slides = document.getElementsByClassName("mySlides");
      var dots = document.getElementsByClassName("dot");
      if (n > slides.length) {slideIndex = 1}    
      if (n < 1) {slideIndex = slides.length}
      for (i = 0; i < slides.length; i++) {
          slides[i].style.display = "none";  
      }
      for (i = 0; i < dots.length; i++) {
          dots[i].className = dots[i].className.replace(" active", "");
      }
      slides[slideIndex-1].style.display = "block";  
      dots[slideIndex-1].className += " active";
    }

    setInterval(function(){ plusSlides(1); }, 3000);
    </script>

    </body>
    </html> 

Upvotes: 0

Swift
Swift

Reputation: 820

// This is simple and easy carousel Slider with indexes i hope this code will help your requirements

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>


<div class="num"></div>

<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel" data-wrap="false" data-interval="false">
  <ol class="carousel-indicators">
    <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
  </ol>
  <div class="carousel-inner">
    <div class="carousel-item item active">
      <img class="d-block w-100" src="https://via.placeholder.com/500x300" alt="First slide">
    </div>
    <div class="carousel-item item">
      <img class="d-block w-100" src="https://via.placeholder.com/500x300" alt="Second slide">
    </div>
    <div class="carousel-item item">
      <img class="d-block w-100" src="https://via.placeholder.com/500x300" alt="Third slide">
    </div>
  </div>
  <a class="carousel-control-prev prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next next" href="#carouselExampleIndicators" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>
<script>
  var totalItems = $('.item').length;
  var currentIndex = $('div.item.active').index() + 1;

  var down_index;
  $('.num').html('' + currentIndex + '/' + totalItems + '');

  $(".next").click(function() {
    currentIndex_active = $('div.item.active').index() + 2;
    if (totalItems >= currentIndex_active) {
      down_index = $('div.item.active').index() + 2;
      $('.num').html('' + currentIndex_active + '/' + totalItems + '');
    }
  });

  $(".prev").click(function() {
    down_index = down_index - 1;
    if (down_index >= 1) {
      $('.num').html('' + down_index + '/' + totalItems + '');
    }
  });
</script>

Upvotes: 1

Related Questions