I felt like trying out a new look for my site but I didn’t want to lose the one I had. So I thought I would leverage all the same pages and just create a new stylesheet and a method of selecting which style to use. Then I thought, I’ll just create a random stylesheet selector as that would just be cool to give people a few different sides of Chase Nelson.
So I began with javascript:
<script>
function chooseStyle() {
var css = new Array('1','2','3');
var i = Math.floor(Math.random()*css.length);
var style = "style"+css[i]+".css";
return style;
}
document.write('<link rel="stylesheet" href="http://www.chasenelson.com/wp-content/themes/default/'+chooseStyle()+'" type="text/css">');
</script>
That works just fine but it will randomly select a stylesheet every time a page loads. So as you navigate through your site it doesn’t maintain the same stylesheet. So I decided to store my selected stylesheet in the session so that if a user comes to my site they will experience the same style for the remainder of that session.
I also decided to switch to PHP because I remembered immediately how to store session variables and I wasn’t using any other javascript in these pages:
<!-- Randomize stylsheet -->
<?php
if(isset($_SESSION['style'])){
$style = $_SESSION['style'];
}
else {
$styles = array('style1.css', 'style2.css', 'style3.css');
$style = array_rand(array_flip($styles), 1);
$_SESSION['style'] = $style;
}
?>
<link rel="stylesheet" href="http://www.chasenelson.com/wp-content/themes/default/<?php echo $style; ?>" type="text/css">
Seems to be working well. As usual there is probably a much easier way to do this… Let me know if there are any improvements that you see.

Angi
June 10, 2010 at 9:44 am
Thanks Chase! You explained something simply that was an issue for me. I appreciate it!