Generate numbers in side div at random position without overlapping
css, javascript, jquery
Solution
You've got most of it figured out. You just need to think of the `.container` div as a grid to avoid any overlap or outlying items.
Just check out this fiddle.
Here's what the code looks like:
var tilesize = 18, tilecount = 15;
var gRows = Math.floor($(".container").innerWidth()/tilesize);
var gCols = Math.floor($('.container').innerHeight()/tilesize);
var vals = _.shuffle(_.range(tilecount));
var xpos = _.shuffle(_.range(gRows));
var ypos = _.shuffle(_.range(gCols));
_.each(vals, function(d,i){
var $newdiv = $('<div/>').addClass("tile");
$newdiv.css({
'position':'absolute',
'left':(xpos[i] * tilesize)+'px',
'top':(ypos[i] * tilesize)+'px'
}).appendTo( '.container' ).html(d);
});
PS:I have used underscore in my fiddle to make things easier for me and because I personally hate writing `for` loops.
Problem
I want to display random numbers inside a div at random positions without overlapping. I am able to display random number at random position but its going outside the box and overlapping each other. Here is my code: JS Fiddle ``` var width = $('.container').innerWidth(); var height = $('.container').innerHeight(); (function generate() { // vary size for fun for (i = 0; i < 15; i++) { var divsize = 12; var color = '#' + Math.round(0xffffff * Math.random()).toString(16); $newdiv = $('<div/>').css({ 'width': divsize + 'px', 'height': divsize + 'px' }); // make position sensitive to size and document's width var posx = (Math.random() * (width - divsize)).toFixed(); var posy = (Math.random() * (height - divsize)).toFixed(); $newdiv.css({ 'position': 'absolute', 'left': posx + 'px', 'top': posy + 'px', 'float': 'left' }).appendTo('.container').html(Math.floor(Math.random() * 9)); } })(); ``` How can I do this?