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.
<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>
the demo code you posted does use Math.random but to just randomly order the divs.
when you said distribution in your original post I thought you meant you wanted to randomly position the divs in terms of their positions from the top and left margins of the browser window.