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>

Recommended Answers

All 2 Replies

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>

Thanks, this affection is what I need.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.