1

I am a little stumped and am probably overlooking something. Basically I have an JS object array:

var defaults = {
    pointers : {
        pointer1 : {
            top : '0px',
            left : '75px',
        },
        pointer2 : {
            top : '310px',
            left : '170px',
        },
        pointer3 : {
            top : '50px',
            left : '80px'
        },
        pointer4 : {
            top : '0px',
            left : '130px',
        },
        pointer5 : {
            top : '310px',
            left : '205px',
        },
        pointer6 : {
            top : '50px',
            left : '90px'
        }
    }
};

If I call them manually to add to a <li> with class pointer-circle it works fine:

$('.pointer-circle:eq(1)').css({
    top : defaults.pointers.pointer1.top,
    left : defaults.pointers.pointer1.left
});

But instead of manually outputting each pointer want them to go through for loop:

var i = 1;
for (i in defaults.pointers) {
    $('.pointer-circle:eq(' + i + ')').css({
        top : defaults.pointers.pointer[i].top,
        left : defaults.pointers.pointer[i].left
    });
}

This does not work. In the console log I am getting this error:

Uncaught TypeError: Cannot read property 'pointer1' of undefined

Any help is greatly appreciated.

1
  • Thanks. This is what happens when I stare at the same code too long. Not sure why I got downvoted though. Just asking for help... Commented Feb 19, 2016 at 21:02

2 Answers 2

2

This is what you're going for :

var counter = 0;
for (i in defaults.pointers) {
    $('.pointer-circle:eq(' + counter + ')').css({
        top : defaults.pointers[i].top,
        left : defaults.pointers[i].left
    });
    counter++;
}

(see also this Fiddle)

Sign up to request clarification or add additional context in comments.

3 Comments

Honestly, I rewrote it a few times so initially it had been the number of <li>, using $('.pointer-circle').length with a regular for loop. So now it ends up being not what I want it to be.
@PlatinumJay : I just updated my code & posted a link to a working Fiddle.
@JohnSlegers thanks, makes sense now. I had changed my mind throughout the code that I ended up mixing myself up.
2

i refers directly to the object. You want just i.top. You are conflating a standard for loop with a for-in loop. Of course, this means that $('.pointer-circle:eq(' + i + ')') is not what you think it is.

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.