1

Why does my imageIndex keep returning -1;

    $(function(){
            //rotateImages();
        setInterval("rotateImages()", 4000);
    });

    var imageIndex = 0;
    var currentPhoto = $("#photoShow div.current");

    function rotateImages(){
        var max = $("#photoShow div").length;
        imageIndex = currentPhoto.index();
        console.log(imageIndex + "    ::   "+ (max - 1));

    }

HTML :

<body>

<div id="photoShow">
    <div class="current">
        <img src="images/Grass.jpg" alt="Photo Gallery" width="400" height="400" class="gallery" />
    </div>
    <div>
        <img src="images/Leaf.jpg" alt="Photo Gallery" width="400" height="400" class="gallery" />
    </div>
    <div>
        <img src="images/Spring.jpg" alt="Photo Gallery" width="400" height="400" class="gallery" />
    </div>
    <div>
        <img src="images/Water.jpg" alt="Photo Gallery" width="400" height="400" class="gallery" />
    </div>
</div>

1
  • Returns 0 for me, which is correct. Commented May 20, 2011 at 4:30

3 Answers 3

3

$.index() returns -1 if the element is not found.

Based on your source code above, it looks like you're not waiting until the DOM is ready before declaring currentPhoto...so chances are the element doesn't exist yet in the DOM when the variable is being defined.

Simply moving everything into $(function(){...}) would give you the results you're expecting.

$(function(){
    //rotateImages();
    setInterval("rotateImages()", 4000);
    var imageIndex = 0;
    var currentPhoto = $("#photoShow div.current");

    function rotateImages(){
        var max = $("#photoShow div").length;
        imageIndex = currentPhoto.index();
        console.log(imageIndex + "    ::   "+ (max - 1));
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

When I moved it all inside the initial jquery function the setInterval can no longer find the function rotateImages(). I get an error:: ReferanceError: Can't find variable: rotateImages
1

Try:

imageIndex = $('#photoShow').index('.current');

Comments

0

This statement var currentPhoto = $("#photoShow div.current"); has length 1 as your code has only one <div class="current">

imageIndex = currentPhoto.index(); should return 0 in that case. In console logs 0 - 1 = -1 is the output

EDIT:
Sorry, your are doing var max = $("#photoShow div").length; and max - 1. imageIndex should be zero :-(

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.