Reputation: 263
So I'm making a simple game and I was wondering how I could assign an image to a random div on page load. For example I have a two rows of div tags that are labeled as such -
<div id="1_1" class="mapsquare"></div>
<div id="2_1" class="mapsquare"></div>
<div id="3_1" class="mapsquare"></div>
<div id="1_2" class="mapsquare"></div>
<div id="2_2" class="mapsquare"></div>
<div id="3_2" class="mapsquare"></div>
I want to be able to add an image (Player sprite) to one of these divs randomly, when the page loads. This is all I have so far, but Im not sure how I could make this work with the div id's.
<script>
function myFunction()
{
var x=document.getElementById("player")
x.innerHTML=Math.floor((Math.random()*6)+1);
}
</script>
Thanks
Upvotes: 0
Views: 285
Reputation: 150050
Perhaps something like this:
var divs = document.querySelectorAll(".mapsquare"),
randomIndex = Math.floor( Math.random() * divs.length );
divs[randomIndex].appendChild(document.getElementById("player"));
Or, sorry, just saw the jQuery tag:
var $divs = $(".mapsquare");
$("#player").appendTo( $divs.get(Math.floor(Math.random() * $divs.length)) );
Basic demo: http://jsfiddle.net/DWfc6/
Of course given that many games involve quite a few random calculations you might like to put the random code into its own function, like this one from MDN:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
Upvotes: 3
Reputation: 680
You can use math.random to get the random div id value like
var divName = Math.ceil(Math.random()*3) + "_" + Math.ceil(Math.random()*3);
and then based on id you can add image
please refer the example DEMO *http://jsbin.com/OqEMoVU/1/edit*
Upvotes: 0
Reputation: 337590
Assuming the #player
element is the image you want to append to a random div, try this:
var $player = $('#player');
var rnd = Math.floor(Math.random() * $('.mapsquare').length);
$('.mapsquare').eq(rnd).append($player);
Upvotes: 1
Reputation: 4868
Try this:
$('div.mapsquare:eq(' + Math.floor(Math.random() * $('div.mapsquare').length) + ')').append(player)
Upvotes: 1