0

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.

2
  • where is the problem? it works fine. Commented Sep 11, 2012 at 14:09
  • put your code to js fiddle and then inspect. the sequence of title is the same as the value showed. Commented Sep 11, 2012 at 14:11

2 Answers 2

1

Add this before $(grp).remove():

for(var i = 0; i < cnt; i ++) {
    grp[i].title = "Row " + (i + 1);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.