0

I have this html:

<div id="h101" data-stellar-ratio="6"><img src="images/h1_01.png" width="600"></div>
<div id="cloud01" data-stellar-ratio="0.5"><img src="images/cloud_01-s.png"></div>
<div id="cloud02" data-stellar-ratio="0.4"><img src="images/cloud_01-s.png"></div>
<div id="island01" data-stellar-ratio="2"><img src="images/island_01.png" width="620"></div>

I create an array from all the id's

$(".section > div").each(function() {
ellementArray.push($(this).attr("id"));});

Now I have all the values in my ellementArray. What I want to do is to create this:

var h101Left = $("#h101").position().left;
var cloud01Left = $("#cloud01").position().left;
var island02Left = $("#island02").position().left;
var island03Left = $("#island03").position().left;

I was thinking something like this...

for (var i = 0; i < ellementArray.length; i++){
        jQuery.globalEval("var ellementArray[i] = ellementArray[i];")
        console.log(ellementArray[i]);
    }

Can somebody please help?

1 Answer 1

3

You're overcomplicating things. Just create a map from string (the element ID) to number (the position-left value):

var leftPositions = {};
$(".section > div").each(function ()
{
    leftPositions[this.id] = $(this).position().left;
});

BTW, if you still need an array of all the IDs, use .map() instead of .each(), and this.id instead of $(this).attr('id'):

var elementArray = $(".section > div").map(function ()
{
    return this.id
}).get();
Sign up to request clarification or add additional context in comments.

2 Comments

Good solution, but then my output will be: h101 = 200; What i need is h101left = 200...
Okay, so change leftPositions[this.id] to leftPositions[this.id + 'left']. Not rocket science.

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.