0

I have 3 divs. I want distribution them random (when refresh the windows, three divs' position will be changed)
I think Math random() can solve this problem, but how to do that? Thanks.

<div id="div1">...</div>
<div id="div2">...</div>
<div id="div3">...</div>
<script>
Math.floor(Math.random()*3)+1;
...
</script>
2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by youlichika
1

OK, if I understand you correctly, you want these divs to be placed in a random order, right? OK, I am going to show you only how to use the random and simply write it out directly to the document. However, there are other advanced and better way to deal with this. You may need to dig into JavaScript more.

<script type="text/javascript">
var order = [1, 2, 3]  // declare as global, and this is the div number
var out = ""  // output to html
var rand      // random number variable to be used in the loop
while (order.length>0) {
  rand = getRandom()
  out += "<div id=\"div"+rand+"\">Displaying Div "+rand+"</div>"
}
document.write(out)

function getRandom() {
  var res = null
  if (order.length==0) { res = null }  // no random, shouldn't be called in this example
  else if (order.length==1) {  // last one left, just return the value inside it
    res = order[0]
    order.pop()
  }
  else {  // get a random element from the array
    var orderLen = order.length
    var rand = Math.floor(Math.random()*orderLen)
    // swap the selected random one with the last element,
    // then get rid of the element
    res = order[rand]
    order[rand] = order[orderLen-1]
    order[orderLen-1] = res
    order.pop()
    // you could check whether the random is the last element and don't need to do swapping,
    // but it would not speed up that much anyway.
  }

  return res  // return the random
}
</script>

Edited by Taywin: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.