This is just a small tip for fun. Sometime, we are bored with the only-one style in our website, but today, we will make some changes. We will create a javascript to randomize the CSS every time we refresh the web page. For what? Just make our style always get new.

Try to refresh the demo page to see the effect.

We will use javascript function Math.random() to generate a random number between 0 and number of elements of an array which is an arrangement of stylesheet items.

Create a new javascript file which contains this function:

function rand(){
    return Math.round(Math.random()*(css.length-1));
}

This gets us numbers from 0 to < (css.length-1) (Because the elements start from 0) which is this array below:

var css = new Array(
    '<link rel="stylesheet" type="text/css" href="default.css">',
    '<link rel="stylesheet" type="text/css" href="style2.css">',
    '<link rel="stylesheet" type="text/css" href="style3.css">',
    '<link rel="stylesheet" type="text/css" href="style4.css">'
);

Then write it in HTML

rand = rand();

document.write(css[rand]);

That’s it! Enjoy the random CSS by refresh your webpage. Your random effect will show clearly if you have many elements in array. The more elements, the less repeat.

PG

Author: Lam Nguyen

I'm Lam Nguyen, a 21 years old web developer writing about a kinds of thing. I am owner of AEXT.NET and also Whofreelance Web Community News. You can also catch me on twitter.

Psd Plus: advanced Photoshop tutorials.

User Comments (5)


  1. Kawsar Ali November 7th, 2009

    Nice . A suggestion. should added a text or something that says refresh the page to see the effect. Might be better for some user

  2. Lam Nguyen November 7th, 2009

    Yes, that’s good for some users. Thanks for the suggestion Kawsar!

  3. Org November 7th, 2009

    Nice, clean and easy!..
    I make something like that in my website!..
    http://pinguinox.com.ar ( work in progress website!.. )

    Saludos!..

  4. Michel Morelli November 8th, 2009

    Great tips.
    Tnx.

  5. clippingimages November 10th, 2009

    Awesome tips. Thanks for sharing this nice post.

Leave a Reply


Please also rate the article as it will help us decide future content and posts. Please no link dropping, no keywords or domains as names; do not spam, and do not advertise!