Search code examples
jqueryreplaceslideshowsrcattr

replacing img src attribute w/ jQuery not working


I'm trying to create simple slideshow where if I click the image it will turn into the next image. So far I have four images in a subfolder, named 1-4 (ex: 1.jpg, 2.jpg, 3.jpg, 4.jpg). I've set up a counter (the variable imgcounter) so that if it is greater than 4 it will reset to 1, and I use this counter to easily change the src name of the img element.

The simple version:

$(document).ready(function() {
var imgcounter = 1; 
$('#slide img').each(function() {
    $(this).click(function() {
        if(imgcounter <= 4 ) {
            imgcounter++;
            $(this).attr('src', 'images/' + imgcounter + '.JPG');
        } // end if
        else {
            var imgcounter = 1;
            $(this).attr('src', 'images/' + imgcounter + '.JPG');
        } // end else
    }); // end click    
}); // end each
});  // end ready

In this version the image will not even change if I click it.

I've also tried this more complicated method where I put a variable to define what I want to replace source with. I'm not sure if I'm using the replace() function right, especially at the part where I used double apostrophes '' to indicate I want to replace the entire src. I'm also not sure if I wrote out the second part of the replace() function legitimately -- the 'images/' + imgcounter + '.JPG'.

$(document).ready(function() {
var imgcounter = 1; 
$('#slide img').each(function() {
    var imgFile = $(this).attr('src');
    var preloadImg = new Image();
    $(this).click(function() {
        if(imgcounter <= 4 ) {
            imgcounter++;
            preloadImg.src = imgFile.replace('', 'images/' + imgcounter + '.JPG');
            $(this).attr('src', preloadImg.src);
        } // end if
        else {
            var imgcounter = 1;
            preloadImg.src = imgFile.replace('', 'images/' + imgcounter + '.JPG');
            $(this).attr('src', preloadImg.src);
        } // end else
    }); // end click    
}); // end each
});  // end ready

In this version the image changed but I get a broken image symbol and the error console reads: Failed to load resource file:///..(took out full path)../images/1.JPGimages/1.JPG I'm not sure why it's failing to replace the entire source and instead it just seems to append a copy of the source name at the end...

Thanks for any help in advance!


Solution

  • I'd do something like:

    var imgcounter = 1;
    
    $("#slide img").click(function(e){
        if(imgcounter < 4){
            imgcounter++;
        }else{
            imgcounter = 1;
        }
        $(this).attr("src", "images/"+imgcounter+".jpg");
    });
    

    It adds the handler to each img inside #slide anyway, so no need for the each() function, and it looks a lot cleaner. Also, removed the redundant call to $(this).attr().