views:

119

answers:

4

I was wondering whats the best way to call a random css file on page refresh with Javascript?

Many thanks

A: 

Append a <link> element on document.ready.

var randomFileName=Math.random(); // or whatever

$(document).ready(function() {
    $('head').append('<link rel="stylesheet" type="text/css" href="' + randomFileName + '.css">');
});

Untested. As mentioned above, it is probably a better (read: more compatible) idea for a server-side script to spit out a random file name directly in the page's HTML instead of using JS trickery.

josh3736
For other peoples reference - This method adds a random number in the href so its impossible to sync with a css file.
Rob
@Rob: The coming up with a file name part was left as an exercise for the reader. :)
josh3736
+4  A: 

If you're using PHP, you can read your CSS directory and pick a random file like this:

<?php
$css_dir = '/css';
$files   = array();

foreach(glob($cssdir.'/*.css') as $file) 
{
    $array[] = $file;
}

echo '<link rel="stylesheet" type="text/css" href="' . array_rand($files, 1) . '">';
?>
Evert
+4  A: 
var link = [];
link[0] = "http://site.com/css/style1.css";
link[1] = "http://site.com/css/style2.css";
link[2] = "http://site.com/css/style3.css";


$(function() {
  var style = link[Math.floor(Math.random() * link.length )];
  $('<link />',{
                rel :'stylesheet',
                type:'text/css',
                href: style
             }).appendTo('head');
});
Ninja Dude
A: 

Thanks for your advice, didn't realise it was possible with a simple line of php and actually found that this method was pretty short and sweet

<link href="/styles/<?php echo mt_rand(1, 5); ?>.css" rel="stylesheet" type="text/css"/>

Found it here, http://forum.mamboserver.com/showthread.php?t=61029

Many thanks

ps. A List Apart also have a pretty simple and brilliant way to switch images, http://www.alistapart.com/articles/randomizer/

Rob