0

I hav an array:

var positions = ["north-america",{"top":512,"left":0},"central-america", {"top":512,"left":85},"united-kingdom",{"top":512,"left":180}];

that I need to itterate over and create a label eg

<div>North America</div>

then position it using the object in the array

<div style="top:512; left:0">North America</div>

I keep getting lost in the iterations using this jQuery.

$.each(positions, function (i, object) {
    $('<div/>', {
        class: 'map-label dragee ' + object,
        region: object
    }).appendTo('#front-end-map');

    $('#labels').append('<h3>' + object + '</h3>');
    $('#labels').append('<span><a href="#">Read More</a></span>').drags();
});

Any help much appreciated.

when I modify to this:

for (var i = 0; i < positions.length; i += 2) {
var name = positions[i];
var pos = positions[i + 1];
     $('<div/>', {
    class: 'map-label ' + name,
    region: name
    }).css({
    top: pos.top + 'px,',
    left: pos.left + 'px'
}).appendTo('#front-end-map');

$('.map-label').append('<h3>' + name + '</h3>');
$('.map-label').append('<span><a href="#">Read More</a></span>').drags();
}

its almost there, but I get no top position in the style attribute, and it still itterates in error, I get 3 elements then 2 then 1??

  • Inspire http://stackoverflow.com/questions/242841/javascript-for-in-vs-for and http://stackoverflow.com/questions/9329446/for-each-in-an-array-how-to-do-that-in-javascript – kubedan Aug 05 '13 at 13:57
  • @user2653332 You didn't need to change your code so much - please see my answer below – MDEV Aug 05 '13 at 14:31

3 Answers3

4

You can't iterate the array as items, because every other item is a city name or a position. You have to iterate the items in pairs. The jQuery each method doesn't support that, so just use a regular loop.

for (var i = 0; i < positions.length; i += 2) {
  var name = positions[i];
  var pos = positions[i + 1];
  var div = $('<div/>', {
    class: 'map-label dragee ' + name,
    region: name
  }).css({
    top: pos.top + 'px',
    left: pos.left + 'px'
  });
  div.appendTo('#front-end-map');

  div.append('<h3>' + name + '</h3>');
  div.append('<span><a href="#">Read More</a></span>').drags();
}

Edit:

You should put the div that you create in a variable, so that you can append elements to that specific element. If you append to $('.map-label') you will be appending the same elements to all labels created so far.

Fixed a typo in the code ('px,' should be 'px',).

Guffa
  • 640,220
  • 96
  • 678
  • 956
  • This is unnecessary - the `.each()` is fine and `.css()` can be passed the whole object with the styles in – MDEV Aug 05 '13 at 14:06
  • @SmokeyPHP: If you use the `each` method, then the first item will be `"north-america"`, the second item `{"top":512,"left":0}`, and so on. It's possible to use, but you will need to do different things every other iteration, and you need a variable to keep the city name in until it can be used in the next iteration. – Guffa Aug 05 '13 at 14:11
  • It's nowhere near as complicated as you're thinking - see my answer. – MDEV Aug 05 '13 at 14:12
  • @SmokeyPHP: It's exactly as complicated as I think. You have extra code to skip every other iteration as the `each` method doesn't support that, and you are accessing an array item other than the one that is iterated because the `each` method can't provide you with that item. – Guffa Aug 05 '13 at 14:15
  • Well yes, one iteration isn't going to provide 2 items, but there's no variable overlaps or different sets of code per iteration, just one if statement and an `index+1` call - barely any change to the OP's original code and simple to read. – MDEV Aug 05 '13 at 14:17
  • @SmokeyPHP: Yes, there is different sets of code per iteration, that's what the extra `if` statement is doing. – Guffa Aug 05 '13 at 14:21
  • *sigh*, never mind. This isn't going anywhere productive it seems. – MDEV Aug 05 '13 at 14:22
  • @user2653332: You are using `append` instead of `appendTo` in the fiddle. There was a typo in my example, `'px,'` should be `'px',`. Also, you should put the `div` that you create in a variable, so that you can append to that specific element. See above. – Guffa Aug 05 '13 at 15:13
0

Just skip the style block indexes and use them from within the iteration of the previous item. Your code is very nearly there, and I have made very few alterations as seen below:

var positions = ["north-america",{"top":181,"left":153},"central-america",{"top":266,"left":196},"united-kingdom",{"top":139,"left":418}];

slugToText = function(text) {
    text = text.replace(/-/g,' ');
    text = text.replace(/(\w+)/g,function(m1,m2) {
        return m2.substr(0,1).toUpperCase() + m2.substr(1)
    });
    return text;
}

$.each(positions,function(i,item) {
    if(i%2==0) //Only do indexes 0,2,4.....
    {
        var mydiv = $('<div/>', {
            class: 'map-label dragee '+item
            ,region: item
        })
        .css(positions[i+1]) //Use the next item along for the styles
        .appendTo("#front-end-map");

        $(mydiv).append('<h3>' + slugToText(item) + '</h3>');
        $(mydiv).append('<span><a href="#">Read More</a></span>');
    }
})
MDEV
  • 10,240
  • 1
  • 29
  • 49
  • smokey, I have posted a fiddle trying to use your solution -can you take a look pls? http://jsfiddle.net/asRVN/11/ – user2653332 Aug 05 '13 at 14:51
  • @user2653332 This is an updated version - your link wasn't actually using my code: [JSFiddle](http://jsfiddle.net/SmokeyPHP/asRVN/14/) I also added a size to the DIVs so they were visible – MDEV Aug 05 '13 at 14:59
  • @user2653332 And updated from your latest link: [jsfiddle](http://jsfiddle.net/SmokeyPHP/7uuqu/2/) -- again, just added more padding to make them more visible. You were only getting 1 before, because `.drags()` was undefined and stopped further processing – MDEV Aug 05 '13 at 15:08
  • so close - if you go to this one you can see how I am trying to get the labels to look and position. This one doesnt itterate past the first one though? Also -many thanks for your help so far...http://jsfiddle.net/3bqwE/3/ – user2653332 Aug 05 '13 at 15:13
  • @user2653332 Yep, was just making that change! [JSFiddle](http://jsfiddle.net/SmokeyPHP/7uuqu/4/) – MDEV Aug 05 '13 at 15:15
  • Smokey - you are the dogs nads - thank you V much. Not a complete days work wasted ... still got 45mins!! – user2653332 Aug 05 '13 at 15:17
  • @user2653332 Updated it again to use proper place names: http://jsfiddle.net/SmokeyPHP/7uuqu/5/ – MDEV Aug 05 '13 at 15:19
0

DEMO

var positions = [{"place":"north-america","top":512,"left":0},{"place":"central-america","top":512,"left":85},{"place":"united-kingdom","top":512,"left":180}];
$.each(positions, function (i, object) {
    console.log(object['top'],i);
    $('<div/>', {
        class: 'map-label dragee ' + object['place'],
        region: object['place'],
        top:object['top']+'px',
        left:object['left']+'px'
    }).appendTo('#front-end-map');
});
Tushar Gupta - curioustushar
  • 54,013
  • 22
  • 95
  • 103