3

I am using localStorage to save CSS information on certain <div>'s. When the user modify's one of these <div>'s, it set's a localStorage item with the following syntax:

ID OF ELEMENT + "-" + x,y, or z (for the different CSS attributes)

So, an example of an item for the x-coordinate of the div #two would be:

two-x

The setting of these works fine, and I can reflect this by doing the following on page load:

$(".drag").css({
"left" : localStorage.getItem("two-x"), 
"top" : localStorage.getItem("two-y"),
"z-index" : localStorage.getItem("two-z"),
});

The page is going to have many div's on it, and I can't hardcode each of them. SO, this brings me to my question... How can I get all the ID's on the page, assign them to a variable, then change the CSS for each ID until they've all been account for?

My attempt at this:

var idtwo = [];
$("body").find("div").each(function(){ idtwo.push(this.id); });
$(".drag").css({
            "left" : localStorage.getItem(idtwo + "-x"), 
            "top" : localStorage.getItem(idtwo + "-y"),
            "z-index" : localStorage.getItem(idtwo + "-z"),
});

The only problem is that the output of idtwo is one,two (when there are two div's on the page with the ID's one and two), where it needs to be just one, run the CSS changes, then two, and run the CSS changes.

Charlie
  • 11,380
  • 19
  • 83
  • 138

2 Answers2

5

Hope this helps.

$('div[id]').each(function() {
    var id = $(this).attr('id');
    $(this).css({
        'left': localStorage.getItem(id + '-x'), 
        'top': localStorage.getItem(id + '-y'),
        'z-index': localStorage.getItem(id + '-z')
    });
});
Farzher
  • 13,934
  • 21
  • 69
  • 100
3

Try this (untested):

$('div', document.body).each(function () {
    var id = $(this).prop('id');

    if (id) {
        $(this).css({
            'left': localStorage.getItem(id + '-x'), 
            'top': localStorage.getItem(id + '-y'),
            'z-index': localStorage.getItem(id + '-z')
        });
    }
});
John Kurlak
  • 6,594
  • 7
  • 43
  • 59
  • I want the CSS to be the most current. If the user drags one of these divs, it will set the position. If the user then closes the page, opens it back up, I want it to be set to the last position. – Charlie Sep 09 '12 at 03:50
  • Fixed according to that description. – John Kurlak Sep 09 '12 at 03:51
  • Are there any major differences between this and Stephen's? – Charlie Sep 09 '12 at 03:55
  • 1
    @Charlie Not really, but, he is using `prop` and I'm using `attr`. The difference is a little confusing, but I think you want to usually use `prop` http://stackoverflow.com/questions/5874652/prop-vs-attr – Farzher Sep 09 '12 at 15:44