/    Sign up×
Community /Pin to ProfileBookmark

PHP CSS Switcher

I saw this in another thread once, I just can’t find it now. I need to be able to let my users pick the background color that they like for my site, and have it be saved in a cookie. Thank you,
Jeffrey

to post a comment
PHP

16 Comments(s)

Copy linkTweet thisAlerts:
@chrysJun 21.2005 — Jeffro,

I posted my [URL=http://www.mytechjournal.com/viewtopic.php?p=66#66]response to your question[/URL] in My Tech Journal. Here it is:

Assuming you have a little knowledge about PHP:

When a user selects his/her background color, I assume it will come from a form, therefore it will be a value in the $_POST array.

[code=php]
$bgcolor = $_POST['bgcolor'];

setcookie( "bgcolor", $bgcolor, 2147483647 );
[/code]


Then, in your code, wherever you are setting the background color, do something like this:

[code=php]
<body bgColor="<?php echo ($_COOKIE['bgcolor']) ? $_COOKIE['bgcolor'] : '#FFFFFF';?>">
[/code]


Assuming you want #FFFFFF to be your default background color.

Let me know how that works out.
Copy linkTweet thisAlerts:
@JeffroauthorJun 21.2005 — so then I would use something like this where the color switcher was:
[code=php]
if ($color == "FFFFFF")
echo ('<form action="index.php" method="post"><input type=hidden name=bgcolor value=FFFFCC><input type="submit" value="Origianl"></form>');
else echo('<form action="index.php" method="post"><input type=hidden name=bgcolor value=FFFFFF><input type="submit" value="White"></form>');[/code]



And put this at the top of the doc:

[code=php]$color = $_COOKIE['bgcolor'];
$bgcolor = $_POST['bgcolor'];
if ($color == "")
setcookie( "bgcolor", "#FFFFCC", 2147483647 );
else
setcookie( "bgcolor", $bgcolor, 2147483647 );[/code]



Wouldn't that be right, because the forum is below the top so the color variable would be set in time?
Copy linkTweet thisAlerts:
@JeffroauthorJun 21.2005 — It works now, but you have to refresh the page to get the new color. Can it be fixed?
Copy linkTweet thisAlerts:
@chrysJun 21.2005 — Once you select your color, you have to refresh the page?

Try this:

[code=php]
if (!$_COOKIE['bgcolor'])
setcookie( "bgcolor", "#FFFFCC", 2147483647 );
else
setcookie( "bgcolor", $_POST['bgcolor'], 2147483647 );

$color = $_COOKIE['bgcolor'];
[/code]
Copy linkTweet thisAlerts:
@JeffroauthorJun 21.2005 — Yea! I got it to work without refereshing the page! Thanks for all of your help!


The Selector at the bottom of the page:
[code=php]<?php echo ('<form action="index.php" method="post"><input type="hidden" name="bgcolors" value="s"><input type=hidden name=bgcolor value=FFFFCC><input type="submit" value="Origianl"></form>
<form action="index.php" method="post"><input type="hidden" name="bgcolors" value="s"><input type="hidden" name="bgcolor" value="CCCCFF"><input type="submit" value="New"></form>'); ?>[/code]


And the body tag:
[code=php]<?php
$bgcolor = $_POST['bgcolor'];
setcookie( "bgcolor", $bgcolor, 2147483647 );?>
<body bgColor="<?php
if ($_POST['bgcolors'] == "s") echo $_POST['bgcolor']; else echo$_COOKIE['bgcolor'] ? $_COOKIE['bgcolor'] : '#CCCCFF';?>">[/code]
Copy linkTweet thisAlerts:
@amazing_andr3Jun 22.2005 — but that's more of a color switcher rather than a CSS switcher. A real CSS switcher should switch an external CSS.
Copy linkTweet thisAlerts:
@LiLcRaZyFuZzYJun 22.2005 — i was gonna say the same! ?
Copy linkTweet thisAlerts:
@_LOBO_Jun 22.2005 — This can help:

Let's start with a very simple way to tell a web page to automatically to use a different style each day.


Basic HTML Test Page

Create a web page as follows:

day.html [code=html]
<html><head><title>Day Trader</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body><h2>Live in Style</h2></body></html> [/code]



This simple web page will always use the same "style.css" style sheet.


Multiple Style Sheets

Create three style sheets named "style0.css", "style1.css", and "style2.css" as follows:
[code=html]
style0.css body { font-family: serif }
h2 { color: steelblue }

style1.css body { font-family: sans-serif }
h2 { color: seagreen }

style2.css body { font-family: cursive }
h2 { color: goldenrod } [/code]


Each of the three style sheets specifies a different font and color.


Static to Dynamic

In the HEAD section of the "day.html" file, replace the line containing the style sheet link with:

New Code (day.html) [code=html]<script>
var StyleFile = "style" + new Date().getDate() % 3 + ".css";
document.writeln('<link rel="stylesheet" type="text/css" href="' + StyleFile + '">');
</script> [/code]


This little bit of JavaScript finds the current day of the month and divides that number by the number of style sheets available (in this case 3). The remainder (in this case 0, 1, or 2) is used to dynamically create the style sheet link based on the day of the month.


Fonts and Colors

Open "day.html" in your browser. If today is the 1st, 4th, 7th, etc. day of the month, you'll see:


If today is the 2nd, 5th, 8th, etc. day of the month, you'll see:


Otherwise, you'll see:


Having a different design each day for your web site may be fun, but it's not really that valuable. Next, we see how to pass control over to the user.


Style Switcher

Now let's add links to the web page so users can change styles on their own. To do this we will set a browser cookie that keeps track of which style was chosen.

It's actually, pretty simple. Here's the HTML code:

switcher.html [code=html]<html><head><title>Style Switcher</title>
<script>
var StyleFile = "style" + document.cookie.charAt(6) + ".css";
document.writeln('<link rel="stylesheet" type="text/css" href="' + StyleFile + '">');
</script>
</head><body><h2>Live in Style</h2><br>
<a href="javascript: document.cookie='style='; window.location.reload();">Style 1</a> |
<a href="javascript: document.cookie='style=2'; window.location.reload();">Style 2</a> |
<a href="javascript: document.cookie='style=3'; window.location.reload();">Style 3</a>
</body></html>[/code]



A few points of interest:

The HREF links use JavaScript to set a browser cookie named "style".

Since we are only setting one cookie and it's name is "style", we can read its value using "document.cookie.charAt(6)".

If no cookie is set, "StyleFile" will evaluate to "style.css".

The files names of the style sheets need to be "style.css", "style2.css", "style3.css", "style4.css", and so on.

Here's what the web page looks like before a style is chosen:



Note that this tutorial is intended to educate through simple examples, and the code and techniques used could certainly be made more robust. If you want to see the power of style sheets, explore "The Beauty of CSS Design" at the Zen Garden.

http://www.centerkey.com/style/switcher/

[B]here with cookies:[/B]

http://www.pmachine.com/plugins/css-switcher/
Copy linkTweet thisAlerts:
@amazing_andr3Jun 22.2005 — hmmm... so what happens if the user doesn't have JavaScript enabled?
Copy linkTweet thisAlerts:
@_LOBO_Jun 22.2005 — well that user just not exist and you not get worried ? ? ?

here the last stats concerning javascript:

[B]JavaScript Stats

Sun May 1 00:01:01 2005 - Tue May 31 23:58:01 2005 31.0 Days[/B]


[B]Javascript 1.2+: 261787782 (95%)[/B]

Javascript <1.2: 512371 (0%)

Javascript false: 11025727 (4%)

this from a sample of:[B]273325880 Visitors[/B]

Main Stats

Sun May 1 00:01:01 2005 - Tue May 31 23:58:01 2005 31.0 Days

[B]273325880 Visitors[/B]

367398 Visitors/hour

my source: http://www.thecounter.com/stats/2005/May/index.php

amazing_andr3: And if you think he shoul think on "4%" of the users that don't have javascript on, post other solution and help us with this problem ? please.

Thank you advance.
Copy linkTweet thisAlerts:
@amazing_andr3Jun 22.2005 — It all depends on who your visitors are. Do a stats on people using this forum and you will see that more than a third have JavaScript disabled.

I strongly recommend the [url=https://addons.mozilla.org/extensions/moreinfo.php?id=722]NoScript Firefox extension[/url] which allows you to specify what sites are allowed to run JavaScript and blocks the rest.
Copy linkTweet thisAlerts:
@JeffroauthorJun 24.2005 — Actually, the way I have it working with php (See above) doesn't require javascript. Thanks for the replys though!!!
Copy linkTweet thisAlerts:
@JeffroauthorJun 24.2005 — but that's more of a color switcher rather than a CSS switcher. A real CSS switcher should switch an external CSS.[/QUOTE]

I could make it switch CSS, but I am happy with the way it works. It may not be as good of code... but whatever. ?
Copy linkTweet thisAlerts:
@bathurst_guyJul 05.2005 — I use a lot of PHP includes in my site, so a lot of this can be written in HTML but I'm too lazy to change it for you, it should make sense to you anyway.

At the moment I have this:

Top of [U]each page[/U] I have this code:
[code=php]<?php
if ($_GET["st"] == "blue"){ // if st = blue
$style = blue; // then the style will be blue
}elseif ($_GET["st"] == "green"){ // if st = green
$style = green; // then the style will be green
}elseif (isset($_COOKIE['COOKIENAME'])) { // if a cookie is set
$style = $_COOKIE['COOKIENAME']; // then the style will be the cookie value
}else{ // if there is no cookie set
$style = green; // set the default style
}
setcookie("COOKIENAME", $style, time()+60*60*24*30, "dir","domain"); // set a cookie with the new style
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'."n";
echo '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">'."n";
echo '<head>'."n";
echo '<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8">'."n";
echo '<title>PHP CSS Switcher</title>'."n";
echo '<link rel="stylesheet" media="all" type="text/css" href="'.$style.'.css">'."n";
echo '</head>'."n";
?>[/code]


Then I included this in [U]each pages[/U] footer:
[code=php]
<?php
echo '<li><a href="index.php?st=green" title="Green Style">Green</a> | </li>'."n";
echo '<li><a href="index.php?st=blue" title="Blue Style">Blue</a></li>'."n";
?>
[/code]


All I want to do now is (which I dont know how to do but am working on it, all input appreciated) is rather than it going to index.php to have another variable which is the page file name so that no matter what page in the site you change the style on, you will remain on that page.

eg
[code=php]echo '<a href="'.$page.'?st=blue" title="Blue Style">Blue</a>';[/code]

Maybe something like $_GET URL .?.?.?


Also I have two different CSS' named blue.css and green.css, this can be extended to heaps, and this first part of code can be changed into this if you want. (Not yet tested!)
[code=php]
if (isset($_GET["st"])){
$style = $_GET["st"];
}elseif(isset($_COOKIE['COOKIENAME'])) {
$style = $_COOKIE['COOKIENAME'];
}else{
$style = green;
}
[/code]
Copy linkTweet thisAlerts:
@_LOBO_Jul 05.2005 — The new Styleswitcher was developed from an idea that came into my head upon using my own styleswitcher on a few sites. The main purpose was to allow multiple stylesheets to be switched independently of one another.

For example, you can allow users to change the layout (or color) of a page without changing the font size and vice versa. You can accomplish this in the old version by creating stylesheets for each option on your page (blue with small text, green with small text, blue with large text, etc.) but I thought this defeated the purpose of multiple stylesheets.

Technically speaking the new version is written using "Object Oriented Programming" (OOP). Basically, the code has been rewritten to allow users to call one body code, not bits and pieces of code. I also hope that this model is actually easier to understand than the previous version (and easier to implement).


http://www.contrastsweb.com/switcher/v2/
Copy linkTweet thisAlerts:
@bathurst_guyJul 05.2005 — UPDATE: Alright I got what I want now to make it work on all pages with as many stylesheets as you want!!! Yey me!

I now have a basic stylesheet set up with all properties except for coloured areas on my site and the colours on there own stylesheets, with the default site colour being green.


Entire new code:
[code=php]
<?php
$page = $HTTP_SERVER_VARS['PHP_SELF'];
if (isset($_GET["st"])){
$style = $_GET["st"];
}elseif(isset($_COOKIE['COOKIENAME'])) {
$style = $_COOKIE['COOKIENAME'];
}else{
$style = green; // default style colour
}
setcookie("COOKIENAME", $style, time()+60*60*24*30, "/","domain"); // set a cookie with the new style
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'."n";
echo '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">'."n";
echo '<head>'."n";
echo '<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8">'."n";
echo '<title>TITLE</title>'."n";

echo '<link rel="stylesheet" media="all" type="text/css" href="style.css">'."n";
echo '<link rel="stylesheet" media="all" type="text/css" href="'.$style.'.css">'."n";
echo '</head>'."n";

echo '<body>'."n";

....


echo '<p>Change this sites stylesheet:<br />'."n";
echo '<ul class="horizontal">'."n";
echo '<li><a href="'.$page.'?st=green" title="Green Style">Green</a> | </li>'."n";
echo '<li><a href="'.$page.'?st=blue" title="Blue Style">Blue</a> | </li>'."n";
echo '<li><a href='''.$page.'?st=purple" title="Purple Style">Purple</a> | </li>'."n";
echo '<li><a href="'.$page.'?st=red" title="Red Style">Red</a></li>'."n";
echo '</ul>'."n";

echo '</body></html>'."n";
?>[/code]
×

Success!

Help @Jeffro spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.15,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...