Reputation: 11765
I want to reorder in which some elements of web page are displayed. Following the answers to this question, I have the following code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
function reorder() {
var grp = $(".myItems").children();
var cnt = grp.length;
var temp,x;
for (var i = 0; i < cnt; i++) {
temp = grp[i];
x = Math.floor(Math.random() * cnt);
grp[i] = grp[x];
grp[x] = temp;
}
$(grp).remove();
$(".myItems").append($(grp));
}
</script>
</head>
<body onload="reorder();">
<div class="myItems">
<div class="item" title="Row 1">1</div>
<div class="item" title="Row 2">2</div>
<div class="item" title="Row 3">3</div>
</div>
</body>
</html>
The problem I have is that I also need to modify the content of the <div>
tags depending on the order in which they appear. In this example, I need the row identifiers in the title
tag to change.
For example, after refreshing, possible results would be:
<div class="myItems">
<div class="item" title="Row 1">2</div>
<div class="item" title="Row 2">1</div>
<div class="item" title="Row 3">3</div>
</div>
or
<div class="myItems">
<div class="item" title="Row 1">3</div>
<div class="item" title="Row 2">2</div>
<div class="item" title="Row 3">1</div>
</div>
Notice that the order of the titles remains the same while the displayed numbers change.
Upvotes: 0
Views: 626
Reputation: 26908
Add this before $(grp).remove()
:
for(var i = 0; i < cnt; i ++) {
grp[i].title = "Row " + (i + 1);
}
Upvotes: 1
Reputation: 66394
Loop over grp
after you've randomised them and for each, reset attribute title
to 'Row '+i
, where i = index in array + 1
.
You can do this during the random step if you do
grp[i].setAttribute('title','Row '+(i+1));
grp[x].setAttribute('title','Row '+(x+1));
This results in calling .setAttribute
many more times but requires one less loop.
Upvotes: 1