Jquery Swap Next/previous Image, Images In Array
I have a literal array of image IDs and I need to swap them in
to Next or Previous image on buttons click events. The initial current image ID is known from the
Solution 1:
Here is an example:
$(function() {
// Image ID arrayvar images = ['240', '260', '250', '123', '200'];
var max = images.length;
// Get current image srcvar curSrc = $('#imageswap').attr('src');
// Find ID in image srcvar curID = curSrc.replace(/.*\/(.*?)\.jpg/i, '$1');
var curIdx = 0;
// Search image list for index of current IDwhile (curIdx < max) {
if (images[curIdx] == curID) {
break;
}
curIdx++;
}
// For conveniencevar imgSrcBase = 'http://placehold.it/';
// Next image on button (and image) click
$('#swapnextimg,#imageswap').click( function() {
curIdx = (curIdx+1) % max;
$("#imageswap").attr('src', imgSrcBase+images[curIdx]+'.jpg');
});
// Prev image on button click
$('#swapprevsimg').click( function() {
curIdx = (curIdx+max-1) % max;
$("#imageswap").attr('src', imgSrcBase+images[curIdx]+'.jpg');
});
});
Solution 2:
Try below code,
var images=["777777","666666","555555"];
var max = $(images).length;
var imgPtr = 0;
$('#swapnextimg').click{
if (imgPtr == max) {
//comment the below return and set imgPtr to 0 for rotating the imagesreturn;
}
$("#imageswap").attr('src', 'http://site.com/images/' + images[imgPtr++] + '.jpg');
}
$('#swapprevsimg').click{
if (imgPtr == 0) {
//comment the below return and set imgPtr to max-1 for rotating the imagesreturn;
}
$("#imageswap").attr('src', 'http://site.com/images/' + images[imgPtr--] + '.jpg');
}
<a id="swapnextimg"></a>
<aid="swapprevsimg"></a><divid="imagebox"><imgid="imageswap"src="http://site.com/images/123456.jpg"></div>
Solution 3:
I assume that you've got one img tag, and only one. And that the purpose of this is to change that single image tag.
To do that you will need the nex and prev button.
<divid="container"><imgsrc="#"data-num="" /><spanclass"prev">prev</span><spanclass"next">next</span></div>
The object:
var obj = [0: 'dog', 1: 'cat'];
now for the next and prev to work. We are going to take a look at the .on()
method.
$('.container span').on('click', function(){
var $this = $(this), // span
currentNum = $this.siblings('img').data('num'), // img data-num
nextNum = $this.is('.next') ? currentNum+1 : currentNum-1, // if class is next add 1, if not remove 1
link = "http://site.com/images/" + obj[nextNum] + ".jpg"// the link// either it's not the last images or it returns
nextNum != obj.length() || return
$('img').attr('src', link).data('num', nextNum)
})
Hope this helped you. If not please let me know
Post a Comment for "Jquery Swap Next/previous Image, Images In Array"