Reputation: 11787
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.
Upvotes: 3
Views: 159
Reputation: 14573
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')
});
});
Upvotes: 5
Reputation: 6680
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')
});
}
});
Upvotes: 3