Taming the Wild Wild Web

Sep 22 2008   3:56PM GMT

Server Side Switch: A No-Javascript CSS Style Switcher



Posted by: Jeffrey Olchovy
PHP, Web development, CSS, Web design, Web standards

Navigate through our previous posts in Taming the Wild Wild Web to view both the overview of this project and the HTML/CSS of our dynamic server side CSS style switcher.

Now that we have the markup and declaratives written, we want our page to be able to switch its stylesheet when the “View alternative page style” link is clicked.

In our example, we’ll achieve such an effect by employing the use of some PHP. Our script will let us know a few things about the page itself; namely, where the request is coming from, what style the page currently has, and what page style the user desires.

We’ll save this information in PHP Sessions rather than cookies; so let’s add the session initialization to the very top of our page.

<?php session_start();  ?>

Next, let’s add some session variables to determine what page our request is coming from and the style currently set by the browser.

$_SESSION['page'] = $_SERVER['REQUEST_URI'];
if (!isset($_SESSION['style'])) {
$_SESSION['style']=’default’;
}

switch ($_SESSION['style']) {
case ‘default’:
$href = ‘css/default.css’;
$title = ‘Default’;
$altHref = ‘css/alt.css’;
$altTitle = ‘Alternate’;
break;
case ‘alt’:
$href = ‘css/alt.css’;
$title = ‘Alternate’;
$altHref = ‘css/default.css’;
$altTitle = ‘Default’;
break;
}

Because this is an awful lot of code to add to the beginning of each of your pages, we’ll throw it into a simple PHP file (style-swap.include.php) and call for it at the top of each page, after our session initialization.

<?php
session_start();
include ’style-swap.include.php’;
?>

The variables that we are setting in our switch will be inserted into our link elements that set the current and alternate style sheets for the Web document.

Therefore, let’s modify our markup to receive these dynamic variables:

<link rel=”stylesheet” type=”text/css” href=”<?=$href;?>” title=”<?=$title;?>” />
<link rel=”alternate stylesheet” type=”text/css” href=”<?=$altHref;?>”  title=”<?=$altTitle;?>” />
Now, we’re almost ready to test our page. We still need to construct our trigger when the link to view the new page style is clicked.

We’ll cover that in the next entry at Taming the Wild Wild Web.

Comment on this Post


You must be logged-in to post a comment. Log-in/Register