0

So I have this funny little problem, where I want to parse the IDs of images. Nothing too complicated... but weirdly enough, my code doesn't seem to work properly. It's weirdddd. Could any care to explain this? I feel blind for not being able to see the error myself.

Here's a snippet of the relevant code that fails to work:

        //Toggling images using img-index variable.
        img-index = 0;
        img-src[0] = $("#ppsfb").attr("id");
        img-src[1] = $("#gty").attr("id");

        $("#cycle").click(function(){
            //Since img-index is just a counter.
            if (img-index < 2){
            img-index = img-index + 1;
            } else {img-index = 0;}                         

            $(img-src[img-index]).fadeIn(1000);             
        });
1
  • not valid variables names, should be [a-zA-Z_$][0-9a-zA-Z_$]* Commented Dec 25, 2011 at 3:56

2 Answers 2

1

img-src is not a valid identifier in JavaScript. That's likely why this is failing.

Check out this fiddle and note the Unexpected token - error

0

img-index is not a valid variable name in JavaScript, you probably want to use img_index or imgIndex. Also, calling attr('id') on something that comes from an ID selector is pointless, $("#ppsfb").attr("id") is 'ppsfb' or nothing. You're probably better off storing whole jQuery objects in img_src too, your $(img-src[img-index]) wouldn't do what you wanted it to do even after fixing the naming problem. Furthermore, you probably want to hide or fadeout the current image before showing the new one.

img_index = 0;
img_src[0] = $('#ppsfb');
img_src[1] = $('#gty');

$("#cycle").click(function(){
    img_src[img_index].hide() // Or .fadeOut or ...
    if(img_index < 2)
        img_index = img_index + 1;
    else
        img_index = 0;
    img_src[img_index].fadeIn(1000);             
});

Presumably you have the positioning, stacking, etc. already sorted out.

1
  • lol, I feel so stupid. It's not that I'm not experienced. I just confused valid name types in HTML and Javascript. I always make bad assumptions with Javascript (since it's so versatile). Commented Dec 25, 2011 at 3:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.