I was wondering whats the best way to call a random css file on page refresh with Javascript?
Many thanks
I was wondering whats the best way to call a random css file on page refresh with Javascript?
Many thanks
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.
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) . '">';
?>
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');
});
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/