Note that there are some explanatory texts on larger screens.

plurals
  1. POreplacing img src attribute w/ jQuery not working
    primarykey
    data
    text
    <p>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. </p> <p>The simple version: </p> <pre><code>$(document).ready(function() { var imgcounter = 1; $('#slide img').each(function() { $(this).click(function() { if(imgcounter &lt;= 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 </code></pre> <p>In this version the image will not even change if I click it.</p> <p>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'.</p> <pre><code>$(document).ready(function() { var imgcounter = 1; $('#slide img').each(function() { var imgFile = $(this).attr('src'); var preloadImg = new Image(); $(this).click(function() { if(imgcounter &lt;= 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 </code></pre> <p>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...</p> <p>Thanks for any help in advance!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload