jQuery – Random Heights and Widths

This is one way to create elements with random heights and widths. The same technique could also be used for any numerical css values.

First it inserts 6 divs into the body with ids of t#, where # is numbers 1-6.

var i=0;
while( i++ < 6) {
	$( "body" ).append('<div id="t' + i + '"></div>'); 
}

I decided that I wanted elements with widths between 100px and 200px, and heights between 100px and 300px. So first it generates a random number between 0 and 200 for width, and 0 and 200 for height, and then adds 100 to each.

var x=0, y=0, i=0;
while( i++ <= 6) {
    x = Math.floor(Math.random() * 100) + 100;
    y = Math.floor(Math.random() * 200) + 100;
    // ...
}

Then for each t# id, it adds the random height and width to the css style.

var x=0, y=0, i=0;
while( i++ <= 6) {
    x = Math.floor(Math.random() * 200) + 100;
    y = Math.floor(Math.random() * 300) + 100;
        $('#t' + i).css({
            width: x,
            height: y
        });
}

View demo

Leave a Reply