View Full Version : Looping and adding a variable number

07-15-2012, 04:44 AM
I am trying to reuse my code: colorswap1, colorswap2 etc but for some reason my script is not doing so! please help

<script type="text/javascript">
$(function() {

var images = ['beige', 'green', 'red','whitebabysmall'];
var max = images.length;

var i = 1-36;

// Get current image src
var curSrc = $('#colorswap'[i]).attr('src');

// Find ID in image src
var curID = curSrc.replace(/.*\/(.*?)\.gif/i, '$1');

var curIdx = 0;

// Search image list for index of current ID
while (curIdx < max) {
if (images[curIdx] == curID) {

// For convenience
var imgSrcBase = '{{ STATIC_URL }}img/creighton/color/';

// Next image on button (and image) click
$('#swapnextimg,#colorswap').click( function() {
curIdx = (curIdx+1) % max;
$("#colorswap").attr('src', imgSrcBase+images[curIdx]+'.gif');

// Prev image on button click
$('#swapprevsimg').click( function() {
curIdx = (curIdx+max-1) % max;
$("#colorswap").attr('src', imgSrcBase+images[curIdx]+'.gif');


07-15-2012, 04:22 PM
You'll need to learn how to use for loops...


This will help you immensely with your understanding of programming and it will be a lot better than simply giving you the answer.

07-16-2012, 07:20 AM
Actually this is a while loop, not a for loop. The while loop is generally more efficient. I'm not sure why it isn't used more often.

I'm having a little trouble visualizing how this code is supposed to work. I can see right off some problems with the red part. This:

var i = 1-36;

says that i = negative 35. I suppose that could be meant to say i could be any number from 1 to 36, that makes more sense.

The use of the $, is distinctively jQuery-ish. Particularly the $(function(){ construct which is shorthand for the jQuery(document).ready(function(){ construct. And the use of .attr(), which is also jQuery syntax. So I'm assuming that:

var curSrc = $('#colorswap'[i]).attr('src');

is some kind of an attempt at a jQuery selector. But it's invalid syntax if it is. There can be no -35th item of any collection. And even if there could (if i is a number from 1 to 36), it would be represented by:


Not as:


But even that isn't how jQuery should be done. You can. what it does is pull the single element from the collection as an ordinary DOM element. But then it cannot be used with the .attr() function. There are at least two ways you could go with that. I'd chose this one:

var curSrc = $('#colorswap').eq(i).attr('src');

But there can be only one element on the page with an id of colorswap anyway. So what you probably mean is:

var curSrc = $('#colorswap' + i).attr('src');

Try that. There could still be other problems with what you're trying to do.

If you want more help, a working demo including the required HTML markup of the code when there was only one colorswap element would be helpful. And we would need to see the current code with it's markup as well.