random position of divs in javascript

Here’s one way to do it. I’m randomly varying the size of the div within a fixed range, then setting the position so the object is always placed within the current window boundaries.

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

    // make position sensitive to size and document's width
    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(100).delay(1000).fadeOut(500, function(){
      $(this).remove();
      makeDiv(); 
    }); 
})();

Edit: For fun, added a random color.

Edit: Added .remove() so we don’t pollute the page with old divs.

Example: http://jsfiddle.net/redler/QcUPk/8/

Leave a Comment