bl4ckbox
bl4ckbox

Reputation: 149

CSS switcher with PHP and Cookie?

How I can create a live style and script switcher like in this page? http://www.momizat.com/theme/goodnews/?

they provide a panel so that visitors can easily change the appearance of the page (css) and also the effect on the menu bar (jquery). Coupled also with a cookie so that when a visitor moves to another page, the customization will remain loaded on the destination page.

I want to apply these function to my site, so my visitor will not bored with just one style, but can vary according to their tastes.

Every answer will be very appreciated. Thanks...

Upvotes: 0

Views: 695

Answers (2)

AardvarkApostrophe
AardvarkApostrophe

Reputation: 285

Okay, if you want to do this with PHP:

0) First, a session must be started on every page or this won't work because a session must be started to either initiate the cookie or access it on next page.

<?php session_start(); ?>

1) You have to write a PHP script that starts in the HEAD tag:

 <?php
 if (isset($_REQUEST['theme']) ) { $_REQUEST['theme'] = $css1; echo "<link rel='text/stylesheet' href='path/to/{$css1}.css'>"; 
    else echo "<link rel='text/stylesheet' href='path/to/default.css'>"; 
 ?>

Okay so now if there is a cookie with a parameter called 'theme' set, the value of that parameter will be served as a css file instead of default.css.

2) Now, you need to give the user an option to switch themes, probably via a drop-down form.

<?php 
echo "<form name='myForm'><select onchange='this.form.submit()' name='theme'>";
echo "<option value='theme1'>Theme 1</option>";
echo "<option value='theme2'>Theme 2</option>";
echo "</select></form>";
?>

Note: I didn't actually run this code, I am sure there are errors but that's just a general overview of how I would do it.

To troubleshoot: make sure the form is being submitted. You can use print_r($_REQUEST); to dump out the contents of the cookie for troubleshooting. Then make sure the path to the CSS file is correct. Finally, once you've got it all working, make sure you're not getting a false result from the CSS file being cached. For instance, in Chrome you can open "Inspect Element" developer tool which will fully refresh the page every time.

Upvotes: 0

Steve
Steve

Reputation: 8640

I haven't looked at the implementation of your example page, but most sites would use this approach:

  • When a user clicks on the theme switcher button,
    • set the new value in the cookie
    • add a specific class name on the body tag (i.e. class="theme1")
  • For every theme, have your CSS start with that class name (i.e. body.theme1 p { color: red; })
  • When the user loads the page, read the cookie and set the class name accordingly.

Upvotes: 3

Related Questions