computer_101
computer_101

Reputation: 1

Add image slider counter via JavaScript

I have the following slider:

    <div class="row">
        <div class="col-md-12">
            <div id="container">
                <img id='slider-img' src='images/img1.png'>
                <div id='left_holder'><img onclick="slider(-1)" class='left' src="images/arrow_left.png"></div>
                <div id='right_holder'><img onclick="slider(1)" class='right' src="images/arrow_right.png"></div>
            </div>
        </div>
    </div>

And the JavaScript that controls the image transitions:

var imagecount = 1;
var totalimage = 11;
function slider(element) {
  var image = document.getElementById("slider-img");
  imagecount = imagecount < totalimage ? imagecount + Number(element) : 1;
  if (imagecount < 1) {
    imagecount = 1;
  };
  image.src = "images/img" + imagecount + ".png";
}

window.onload = function() {
  slider(0);

}

I have 11 images at the moment in an images folder and I would like to add a counter to the bottom right of the slider. Something like 1/11 etc... and I would need it to wrap around of course so after 11/11, clicking on the right arrow will show a caption of 1/11.

Upvotes: 0

Views: 1981

Answers (1)

Gary Storey
Gary Storey

Reputation: 1814

You can simply add a div to show the information. You already know the count and the total.

<div id="showCount"></div>

And in the JS:

var showCount=$('#showCount');
function slider(element) {
  var image = document.getElementById("slider-img");
  imagecount = imagecount < totalimage ? imagecount + Number(element) : 1;
  if (imagecount < 1) {
    imagecount = 1;
  }
  image.src = "images/img" + imagecount + ".png";
  showCount.text( imagecount + '/' + totalimage );
}

BTW, you do not need a semi-colon at the end of the if.

Update: Use CSS to position the div wherever you need it. I do not recommend using JS for that.

Upvotes: 1

Related Questions