Reputation: 229
After dragging divs in my javascript application... I want to assign a numeric class to all divs, ordered by the position. I've researched a lot, and builded the next... but it just does not work. (Inner HTML does not change)
var ele = document.getElementsByTagName("div");
var i = 0;
var MyDrags = [];
while(ele[i]) {
if(ele[i].id.substr(0, 4)=="drag") {
MyDrags["distance"]=parseInt(document.getElementById(ele[i].id).style.top,10);
MyDrags["id"]=ele[i].id;
}
i++;
}
MyDrags.sort(function(a,b) {
return a.distance - b.distance;
});
i = 0;
while(MyDrags["distance"][i]) {
document.getElementById(MyDrags["id"][i]).innerHTML=MyDrags["distance"][i];
i++;
}
Upvotes: 0
Views: 178
Reputation: 16605
This is because you are overwriting the previous values, you need to assign a new object in each iteration, to have your code working, it should look like this:
var ele = document.getElementsByTagName('div');
var i = 0;
var MyDrags = [], dst;
while (ele[i]) {
if (ele[i].id.substr(0, 4) === 'drag') {
MyDrags.push({
distance: parseInt(document.getElementById(ele[i].id).style.top, 10),
id: ele[i].id
});
}
i++;
}
MyDrags.sort(function(a, b) {
return a.distance - b.distance;
});
i = 0;
while(MyDrags[i]) {
if (dst = MyDrags[i]['distance']) {
document.getElementById(MyDrags[i]['id']).style.top = dst + 'px';
document.getElementById(MyDrags[i++]['id']).innerHTML = dst;
}
}
Upvotes: 2