1
votes

So basically I have a gallery script in jQuery. When a user clicks on a thumbnail image the image attribute src is then transferred to the main gallery img element. However I now want the user to be able to click a next/prev button and iterate through all the images in the folder. I named them all img0.jpg, img1.jpg and so on. I was thinking I could simply get the current img src via "attr()" and "slice()" then increment the number in the img'0', img'1' etc... with a variable. Heres my code. I hope you guys can understand!

$("#next").click(function () {
   var i = 0;
   var sliceImg = $("#gallerycover").attr("src").slice('0', String.length - 5);
   $("#gallerycover").attr("src", sliceImg + i++ +."jpg");
});
<div id="gallerycontainer">
  <img id="gallery" src="" />
</div>

<div id="thumbcontainer">
  <div id="box4"><img class="thumb" src="" /></div>
</div>
3

3 Answers

1
votes

Try replacing your following code:

var sliceImg = $("#gallerycover").attr("src").slice('0', String.length - 5);
$("#gallerycover").attr("src", sliceImg + i++ +."jpg");

for this one:

var src = $("#gallerycover").attr("src");
var idx = src.indexOf('img');
var sliceImg = src.slice(idx+3, src.length - 4);
$("#gallerycover").attr("src", (parseInt(sliceImg, 10) + 1) + ".jpg");

See working demo

0
votes

you can use a regular expression to split up your image source string, or you can have your slider keep better track of individual slides by adding an attribute to the thumbnail that your next/previous functions can check and increment without having to parse strings (which can possibly change in the future).

0
votes
var myInt = 0;
var myInt++;

var sliceImg = $("#gallerycover").attr("src").replace(/\d+/, myInt);

$("#gallerycover").attr("src", sliceImg);