0

I would simply like to prevent the random divs from overlapping. I have tried adding a margin, floating left, and adding a border. Nothing has worked thus far.

http://jsfiddle.net/QcUPk/2349/

(function makeDiv(){
    var divsize = ((Math.random()*100) + 50).toFixed();
    var num = 2;
    var percent = 10;
    var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
    $newdiv = $('<div/>').css({
        'width':divsize+'px',
        'height':divsize+'px',
        'background-color': color,
        'border':num+'px'
    });

    var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
    var posy = (Math.random() * ($(document).height() - divsize)).toFixed();

    $newdiv.css({
        'position':'absolute',
        'left':posx+'px',
        'top':posy+'px',
        'display':'none'
    }).appendTo( 'body' ).fadeIn(1000, makeDiv).delay(4000).fadeOut(200, function(){
       $(this).remove();
    }); 
})();
Stephen Tafler
  • 107
  • 1
  • 3
  • 11
  • You're using `position: absolute` and thus `margin` has no effect on the elements. You have to implement a collision detection. – KittMedia Mar 29 '14 at 08:16
  • `position: float` used with `float: left` will fill viewport with non-overlapping divs, but random positioning will be lost obviously. You could put more white divs for spacing, but effect won't be the same. For identical effect less overlaps, the only way seems to be KittMedia's suggestion of collision detection. – fzzylogic Mar 29 '14 at 08:27
  • @StephenTafler Your jsfiddle code and the code given here is not same please edit . – Vishal Nair Mar 29 '14 at 08:30
  • @Stephen I like this effect thanks for posting – Pravin W Mar 29 '14 at 09:04
  • If you use collision detection remember you would have to store the position and divsize of all the divs which are displayed at a particular instance and this will change according to your `fadeIn` , `delay` and `fadeOut` values like for example for fadeIn `1000` , delay `4000` and fadeOut `200` , max 5 divs are displayed on the screen so you would have to store the position and divsize of last 5 divs that were generated everytime and then create the new one which don't overlap with any of those 5 divs. – Vishal Nair Mar 29 '14 at 09:15
  • I will research collision detection and post my findings here. Also, here is what I am trying to accomplish. This question is just a piece of my final solution. http://stackoverflow.com/questions/22726914/simultaneously-squares-on-pages-fading-in-and-out-with-javascript – Stephen Tafler Mar 29 '14 at 13:08

0 Answers0