I am creating an image gallery where a user can click "next" and the images will update with the next images. All of the images should update to different images than were currently displayed.
For example once the next button is clicked:
- Image01 --> Image04
- Image02 --> Image05
- Image03 --> Image06
HTML:
<div class="socialItem">
<img class="socialImage" src="http://placehold.it/240.jpg" width="290" height="250" alt="" />
</div>
<div class="socialItem">
<img class="socialImage" src="http://placehold.it/250.jpg" width="290" height="250" alt="" />
</div>
<div class="socialItem">
<img class="socialImage" src="http://placehold.it/260.jpg" width="290" height="250" alt="" />
</div>
<a id="swapnextimg">Next</a>
JQuery:
$(function() {
var images = ['240', '250', '260', '123', '200'];
var max = images.length;
$('#swapnextimg').click( function() {
$(".socialImage").each(function(index) {
console.log( index + ": " + $( this ).attr('src') );
// Get current image src
var curSrc = $(this).attr('src');
// Find ID in image src
var curID = curSrc.replace(/.*\/(.*?)\.jpg/i, '$1');
var curIdx = 0;
// Search image list for index of current ID
while (curIdx < max) {
if (images[curIdx] == curID) {
break;
}
curIdx++;
}
// For convenience
var imgSrcBase = 'http://placehold.it/';
// Next image on button (and image) click
curIdx = (curIdx+1) % max;
$(this).attr('src', imgSrcBase+images[curIdx]+'.jpg');
});
});
});
This code is adapted partially from this answer.
I am attempting to use .each to incrementally replace the sources of each image individually that has the socialImage class. However it is instead replacing all of the images with that class at once.
curIDwhen you are using/.*\/(.*?)\.jpg/ionhttp://placehold.it/50/? ;)