/    Sign up×
Community /Pin to ProfileBookmark

Hi !!!
I have a great css switcher ( javascript ) made by a friend, and I would like to add cookies to it, so that the user gets the same page everytime he comes in.
I have to do it in javascript. It’s complicated, but it HAS to be javascript ( I tried php, and I couldn’t get what I wanted ).
So, I wonder.
Is there a way I can write a cookie with this javascript function, and then get it back when the user comes back on the page ?
Sorry, my explanations are a bit messy…
I’ll show you the switcher.

[code=php]
function switchCSS(val){
document.getElementById(‘pStyle’).href=’css’+val+’.css’;
styleSheet=’css’+val+’.css’
[/code]

that’s only one part, because the rest is not important.
in the head tag, I have this :

[code=php]
<link rel=”stylesheet” href=”css1.css” type=”text/css” id=”pStyle”>
[/code]

A cookie would be great. On my previous try, i had cookies, and a cookiecheck file who would do the job, but the rest was not okay with my website…

Any help would be awesome !!!
Thanks !
Ness

to post a comment
PHP

17 Comments(s)

Copy linkTweet thisAlerts:
@96turnerriApr 17.2005 — I have to do it in javascript. It's complicated, but it HAS to be javascript [/QUOTE]
so why are you posting in PHP forum?
Copy linkTweet thisAlerts:
@Ness_du_FratauthorApr 18.2005 — Because I need php to make the cookies ! ( unless you can make them in javascript ? But you have to read them in php, no ? )
Copy linkTweet thisAlerts:
@gaston9x19Apr 18.2005 — You're misinformed. It's very possible to write cookies in Javascript.

Use document.cookie('cookieName=cookieData'); to create a simple session cookie. For persistent cookies, you add an expiration date next, same way as PHP does things. The date has to be formatted in a certain way:

Wdy, DD-Mon-YYYY HH:MM:SS GMT

Or you can set it using the date() object. This sets the expiration date to one year from the current date, then sets a persisten cookie:

<i>
</i>var expiration=new Date();
expiration.setFullYear(expiration.getFullYear() + 1);
expiration=expiration.toGMTString();

document.cookie('cookieName=cookieData;expires='+expiration);


These are all the parameters you can set for cookies:

name=value; expires=date; path=pathname; domain=domainname; secure=bool

Only the name=value pair is required. To delete the cookie set the expiration date to sometime in the past:

<i>
</i>var diedate=new Date();
diedate.setFullYear(diedate.getFullYear() - 1);
diedate=diedate.toGMTString();

document.cookie('cookieName=;expires='+diedate);


You CAN read the cookies in Javascript, but it's a lot more complicated than in PHP. PHP stores all cookies for that document in an array, Javascript is just one long string, so you have to use substr and length quite a bit, but here's a function I use to search for a get cookie data in Javascript:

<i>
</i>function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length &gt; 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) { // if the cookie exists
offset += search.length
end = document.cookie.indexOf(";", offset); // set the index of beginning value

<i> </i>if (end == -1) // set the index of the end of cookie value
<i> </i> end = document.cookie.length;
<i> </i> returnvalue=unescape(document.cookie.substring(offset, end))
<i> </i> }
}
return returnvalue;
}


When you run, say, get_cookie('cookieName'), you get back either the data in that cookie, or an empty string if that cookie doesn't exist.

Hope this helps ?
Copy linkTweet thisAlerts:
@gaston9x19Apr 18.2005 — Dudes, if a moderator reads this, can you please tell me what's screwed up with your forums? It keeps introducing whitespace in posts that mess up scripts. Look at the get_cookie function, near the end, it changed "offset" to "off set". This will cause the script not to work anymore if someone copies and pastes it. That kinda sucks.

Ness_du_Frat, I'm sorry, but you'll have to change that to get the function to work. It wasn't me.
Copy linkTweet thisAlerts:
@Ness_du_FratauthorApr 18.2005 — thanks a lot !!

I'll try that this evening. I'll let you know if it worked for my website !!! ?
Copy linkTweet thisAlerts:
@Ness_du_FratauthorApr 18.2005 — You're misinformed. It's very possible to write cookies in Javascript.

Use document.cookie('cookieName=cookieData'); to create a simple session cookie. For persistent cookies, you add an expiration date next, same way as PHP does things. The date has to be formatted in a certain way:

Wdy, DD-Mon-YYYY HH:MM:SS GMT

Or you can set it using the date() object. This sets the expiration date to one year from the current date, then sets a persisten cookie:

<i>
</i>var expiration=new Date();
expiration.setFullYear(expiration.getFullYear() + 1);
expiration=expiration.toGMTString();

document.cookie('cookieName=cookieData;expires='+expiration);


These are all the parameters you can set for cookies:

name=value; expires=date; path=pathname; domain=domainname; secure=bool

Only the name=value pair is required. To delete the cookie set the expiration date to sometime in the past:

<i>
</i>var diedate=new Date();
diedate.setFullYear(diedate.getFullYear() - 1);
diedate=diedate.toGMTString();

document.cookie('cookieName=;expires='+diedate);


You CAN read the cookies in Javascript, but it's a lot more complicated than in PHP. PHP stores all cookies for that document in an array, Javascript is just one long string, so you have to use substr and length quite a bit, but here's a function I use to search for a get cookie data in Javascript:

<i>
</i>function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length &gt; 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) { // if the cookie exists
offset += search.length
end = document.cookie.indexOf(";", offset); // set the index of beginning value

<i> </i>if (end == -1) // set the index of the end of cookie value
<i> </i> end = document.cookie.length;
<i> </i> returnvalue=unescape(document.cookie.substring(offset, end))
<i> </i> }
}
return returnvalue;
}


When you run, say, get_cookie('cookieName'), you get back either the data in that cookie, or an empty string if that cookie doesn't exist.

Hope this helps ?[/QUOTE]

Ok, my knowledge of cookies being extremely small, I have no idea how to implement this in my css switcher... ?

When do I have to call for the get_cookie fonction ? The name of the cookie doesn't change, right ? I'm loooooooooost !!!!!

I'd like a cookie who remembers the value of my variable called 'val'. How can I do this ???


BTW, when I was saying "javascript only", this refered to the css switcher only, not to the cookies !!! ( but I have to admit that even myself wondered why I explained it so badly in the first post ).

Any idea how that can be done ???? ?
Copy linkTweet thisAlerts:
@gaston9x19Apr 18.2005 — lol ah, k, well I kinda like working with cookies in Javascript easier anyway. You don't have to reload the page.

Ok, you want to set a cookie that remembers the value of 'val', right? Ok, when you switch the template or whatever, use a little bit of Javascript to set the persistent cookie:

<i>
</i>document.cookie('val=data;expires='+expiration);


This is assuming you have the expiration setting thing and the get_cookie function in a script in your header. Ok, next when you want to get the cookie info back, you call the get_cookie function because it seraches the cookie string, finds the cookie you named, if it exists, and returns the data. See, with PHP you could get the data back by simply using the value for $_COOKIE['val'], with Javascript you have to search the string of data for all cookies. That's why the get_cookie function is so important. It makes finding just the one cookie you want easy ?

If the cookie hasn't been set it returns an empty string, so you could use the cookie value if one has been set, or some other value if it hasn't kinda like this:

<i>
</i>if(get_cookie('val')==""){ code to execute if there is no cookie }else{ do something with the output from get_cookie('val') }
Copy linkTweet thisAlerts:
@Ness_du_FratauthorApr 19.2005 — Thanks a lot !!! I'll try that ASAP and let you know if I finally managed to make it work !!!!
Copy linkTweet thisAlerts:
@Ness_du_FratauthorApr 22.2005 — Ok, it's me again, and... it doesn't work !!!! ?

Here is the whole page code...
[code=php]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Les Enfants de l'&Ocirc; - version 3.0 - Mayi</title>
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="css1.css" type="text/css" id="pStyle">
<base target="iframe1">
<script src="index.js"></script>
<script type="text/javascript">
<!--
function P7_writeStyles(op,a){ //v1.5 by PVII
if(op==0||document.getElementById){var tS="<sty"+"le type="text/css">";
tS+=a+"<"+"/sty"+"le>";document.write(tS);document.close();}
}
P7_writeStyles(1,'.closed ul{display:none;}.open ul{display:block;}');
var styleSheet='css1.css';
var startcolor= new Array(255,255,255); // start color (red, green, blue)
var endcolor=new Array(0,0,0); // end color (red, green, blue)
//cookie stuff here
var expiration=new Date();
expiration.setFullYear(expiration.getFullYear() + 1);
expiration=expiration.toGMTString();



function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) { // if the cookie exists
offset += search.length
end = document.cookie.indexOf(";", offset); // set the index of beginning value

if (end == -1) // set the index of the end of cookie value
end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}

function cookie() {
if(get_cookie('val')==""){
document.getElementById('pStyle').href='css1.css';
styleSheet='css'+val+'.css'
}
else {
document.getElementById('pStyle').href='css'+get_cookie('val')+'.css';
styleSheet='css'+val+'.css'
}
}
//-->
</script>
<!--[if gte IE 5]>
<style>
#p7swapmenu ul a {height: 1em;}
</style>
<![endif]-->
<!--[if IE 5]>
<style>
#p7swapmenu li {margin-top: -3px;}
</style>
<![endif]-->
</head>
<body class="body" onload="document.urlForm.cUrl.value='http://psychomoa.free.fr/'+document.getElementById('iframe1').src;cookie()">
<div id="titre"></div>
<div id="logo"></div>
<div id="p7swapmenu">
<ul>
<li id="menu"></li>
<li class="closed" id="p1"><a href="#" onClick="P7_swapClass(1,'p1','open','closed','li');return false" target="_top"><img src="plus.gif" border="0">
Histoire</a>
<ul>
<li><a href="histoire1.htm" onclick="document.urlForm.cUrl.value=this.href">Premi&egrave;re Partie <img src="moins.gif" border="0"></a></li>
<li><a href="histoire2.htm" onclick="document.urlForm.cUrl.value=this.href">Deuxi&egrave;me Partie <img src="moins.gif" border="0"></a></li>
<li><a href="histoire3.htm" onclick="document.urlForm.cUrl.value=this.href">Annexes <img src="moins.gif" border="0"></a></li>
</ul>
</li>
<li class="closed" id="p2"><a href="#" onClick="P7_swapClass(1,'p2','open','closed','li');return false"><img src="plus.gif" border="0">
Personnages</a>
<ul>
<li><a href="#">Premi&egrave;re Partie <img src="moins.gif" border="0"></a></li>
<li><a href="#">Deuxi&egrave;me Partie <img src="moins.gif" border="0"></a></li>
<li><a href="#">G&eacute;n&eacute;alogie <img src="moins.gif" border="0"></a></li>
<li><a href="#">Quickref <img src="moins.gif" border="0"></a></li>
</ul>
</li>
<li class="closed" id="p3"><a href="#" onClick="P7_swapClass(1,'p3','open','closed','li');return false"><img src="plus.gif" border="0">
Galerie</a>
<ul>
<li><a href="#">Premi&egrave;re Partie <img src="moins.gif" border="0"></a></li>
<li><a href="#">Deuxi&egrave;me Partie <img src="moins.gif" border="0"></a></li>
<li><a href="#">Wallpapers <img src="moins.gif" border="0"></a></li>
<li><a href="#">Autres <img src="moins.gif" border="0"></a></li>
</ul>
</li>
<li class="closed" id="p5"><a href="#" onClick="P7_swapClass(1,'p5','open','closed','li');return false"><img src="plus.gif" border="0">
Bonus</a>
<ul>
<li><a href="chat.htm">Tagboard <img src="moins.gif" border="0"></a></li>
<li><a href="#">&szlig;-Lectrices <img src="moins.gif" border="0"></a></li>
<li><a href="#">Chapitres Bonus <img src="moins.gif" border="0"></a></li>
<li><a href="#">Tentacule D&eacute;&ccedil;u <img src="moins.gif" border="0"></a></li>
<li><a href="#">Casting <img src="moins.gif" border="0"></a></li>
<li><a href="#">Espace Membres <img src="moins.gif" border="0"></a></li>
</ul>
</li>
<li class="closed" id="p4"><a href="#" onClick="P7_swapClass(1,'p4','open','closed','li');return false"><img src="plus.gif" border="0">
Divers</a>
<ul>
<li><a href="#">Livre de Platine <img src="moins.gif" border="0"></a></li>
<li><a href="version2.htm">Site <img src="moins.gif" border="0"></a></li>
<li><a href="faq.htm">F.A.Q. <img src="moins.gif" border="0"></a></li>
<li><a href="#">Remerciements <img src="moins.gif" border="0"></a></li>
<li><a href="#">Plan du Site <img src="moins.gif" border="0"></a></li>
<li><a href="#">NesS <img src="moins.gif" border="0"></a></li>
</ul>
</li>
<li class="closed" id="p6"><a href="#" onClick="P7_swapClass(1,'p6','open','closed','li');return false"><img src="plus.gif" border="0">
Liens</a>
<ul>
<li><a href="chat.htm">Lier LE&Ocirc; <img src="moins.gif" border="0"></a></li>
<li><a href="#">Mailing-List <img src="moins.gif" border="0"></a></li>
<li><a href="#">Romans en Ligne <img src="moins.gif" border="0"></a></li>
<li><a href="#">Sites d'Amis <img src="moins.gif" border="0"></a></li>
<li><a href="#">Divers <img src="moins.gif" border="0"></a></li>
</ul>
</li>
<li id="bas"></li>
</ul>
</div>


<div id="titrenews"></div>

<div id="newsbas"></div>
<div id="news">
<script src="scroller.js"></script>
</div>
<div id="frame">
<iframe id="iframe1" name="iframe1" width="100%" height="100%" frameborder="0" src="edito2.htm"></iframe>
</div>
[/code]

the rest is in the next post... it was too long...
Copy linkTweet thisAlerts:
@Ness_du_FratauthorApr 22.2005 — [code=php]
<div id="version">
<a href="#" target="IFrame2" onmousedown="sTop=top.frames['iframe1'].document.getElementsByTagName('body')[0].scrollTop" onclick="switchCSS(1);return false">White</a>
<!-- <a href="versioncheck2.php?newskin=1" target="IFrame2" onmousedown="sTop=top.frames['iframe1'].document.getElementsByTagName('body')[0].scrollTop" onclick="switchCSS(1);">White</a> -->
<a href="#" target="IFrame2" onmousedown="sTop=top.frames['iframe1'].document.getElementsByTagName('body')[0].scrollTop" onclick="switchCSS(2);return false">Violet</a>
<!-- <a href="versioncheck2.php?newskin=2" target="IFrame2" onmousedown="sTop=top.frames['iframe1'].document.getElementsByTagName('body')[0].scrollTop" onclick="switchCSS(2);">Violet</a> -->
<a href="#" target="IFrame2" onmousedown="sTop=top.frames['iframe1'].document.getElementsByTagName('body')[0].scrollTop" onclick="switchCSS(3);return false">Orange</a>
<!-- <a href="versioncheck2.php?newskin=3" target="IFrame2" onmousedown="sTop=top.frames['iframe1'].document.getElementsByTagName('body')[0].scrollTop" onclick="switchCSS(3);">Orange</a> -->
<a href="#" target="IFrame2" onmousedown="sTop=top.frames['iframe1'].document.getElementsByTagName('body')[0].scrollTop" onclick="switchCSS(4);return false">Bleu</a>
<!-- <a href="versioncheck2.php?newskin=4" target="IFrame2" onmousedown="sTop=top.frames['iframe1'].document.getElementsByTagName('body')[0].scrollTop" onclick="switchCSS(4);">Bleu</a> -->
<a href="#" target="IFrame2" onmousedown="sTop=top.frames['iframe1'].document.getElementsByTagName('body')[0].scrollTop" onclick="switchCSS(5);return false">Vert</a>
<!-- <a href="versioncheck2.php?newskin=5" target="IFrame2" onmousedown="sTop=top.frames['iframe1'].document.getElementsByTagName('body')[0].scrollTop" onclick="switchCSS(5);">Vert</a> -->
</div>
<div id="versiontitre"></div>
<form name="urlForm" action="#">
<input type="hidden" name="cUrl" value="">
</form>
<script language="JavaScript" type="text/javascript">
<!--
var sTop;
var ns=(!document.all&&(navigator.vendor=='Netscape'||navigator.vendor=='Netscape6')&&!window.opera)
//window.onerror=function(e){if(ns)return true;}
//window.onerror=function(e){if(ns)alert(e);return true;}
function switchCSS(val){
document.getElementById('pStyle').href='css'+val+'.css';
document.cookie('val=data;expires='+expiration);
styleSheet='css'+val+'.css'


if (val==1)
{
strt='Mayi';
startcolor= new Array(255,255,255); // start color (red, green, blue)
endcolor=new Array(0,0,0); // end color (red, green, blue)
}
if (val==2)
{
strt='Asla';
startcolor= new Array(153,102,255); // start color (red, green, blue)
endcolor=new Array(0,0,0); // end color (red, green, blue)

}
if (val==3)
{
strt='Okhanan';
startcolor= new Array(255,153,51); // start color (red, green, blue)
endcolor= new Array(0,0,0); // end color (red, green, blue)
}
if (val==4)
{
strt='Isaac';
startcolor= new Array(102,102,255); // start color (red, green, blue)
endcolor=new Array(0,0,0); // end color (red, green, blue)
}
if (val==5)
{
strt='Lúka';
startcolor= new Array(153,255,153); // start color (red, green, blue)
endcolor=new Array(0,0,0); // end color (red, green, blue)
}
document.title="Les Enfants de l'Ô - version 3.0 - "+strt;

if(ns){
if(typeof(top.frames['iframe1'])=='object'){
document.getElementById('iframe1_1').src =document.urlForm.cUrl.value;
//alert(top.frames[0].document.getElementById('p1').nodeName)
top.frames[0].document.getElementById('cStyle').href='css'+val+'.css';
//document.getElementById('iframe1_1').document.getElementById('cStyle').href='css'+val+'.css';
}
}
else{
sTop+=0;
top.frames['iframe1'].document.getElementById('cStyle').href='http://psychomoa.free.fr/css'+val+'.css';
if(navigator.vendor=='Firefox'){
setTimeout("top.frames['iframe1'].window.scrollTo(0,"+sTop+")",250);
}
else{
top.window.frames['iframe1'].window.scrollTo(0,sTop)
}
}
top.window.frames['IFrame2'].location.href='versioncheck2.php?newskin='+val;
}
//-->
</script>
<iframe name='IFrame2' id='IFrame2' style="width:0;height:0;border:none;" frameborder="0"></iframe>
</body>
</html>
[/code]


In my function switchcss, the cookie thing breaks the inner pages css thing...

function switchCSS(val){

document.getElementById('pStyle').href='css'+val+'.css';

document.cookie('val=data;expires='+expiration);

styleSheet='css'+val+'.css'

Normally, the inner page ( in the iframe ) takes the parent's style, and now it doesn't anymore...

The cookies doesn't work either, I tested the page, and it's always the default page which comes...

I'm sure your script is perfectly ok, but I'm really dumb and I can't manage to make it work on my page.... ?
Copy linkTweet thisAlerts:
@gaston9x19Apr 23.2005 — Ok, I think I see the reason the cookie isn't being set, it was my mistake, I started blending the two languages together. In Javascript, you'd set the cookie like this:

document.cookie="name=data";

My mistake, sorry about that. To figure out what was going on, I took just the basics from your code, and wrote something similar. It just changes the stylesheet used and sets the cookie. I'm sure you have another method of initiating switchCSS(), but see if this isn't close to something you can use. The plain-text code:

http://gaston9x19.modcentral.us/test/French_cookies_code.php

And the working test page:

http://gaston9x19.modcentral.us/test/French_cookies.php


I hope this works a little better for ya.
Copy linkTweet thisAlerts:
@Ness_du_FratauthorApr 23.2005 — Na, it doesn't work... But I think I know why. Actually, in the page, you have a style sheet which is defined by default, and I think it's here that i need to put a cookie check or something, but I have no idea how to do it...

Let me explain a bit more what I need :

In the header, you have this piece of code :
[code=php]
<link rel="stylesheet" href="css1.css" type="text/css" id="pStyle">
[/code]

And then, a bit further :
[code=php]
var styleSheet='css1.css'; // that's javascript
[/code]

The two lines are essential for the deisgn. But if there is a way to put the cookie value inside of it when the page loads, it would work, I think...

The problem is that I have no idea on how to do that... Maybe with some php ? ? It's too hard, I'm starting to HATE my new website...
Copy linkTweet thisAlerts:
@gaston9x19Apr 23.2005 — Aw, you'll get it, that's why we're here, to help each other out with probs. Isn't the cookie() function enough to check for a cookie and change the stylesheet in use? It seems to do that pretty reliably in my test page. If this isn't direct enough, you might try something like this, placing the external stylesheet after the cookies code in the header:

<i>
</i>&lt;script type="text/javascript"&gt;
if(get_cookie('val')==""){
document.write("&lt;link rel="stylesheet" href="css1.css" type="text/css" id="pStyle"&gt;");
}else{
document.write("&lt;link rel="stylesheet" href="css"+get_cookie('val')+".css" type="text/css" id="pStyle"&gt;");
}
&lt;/script&gt;


Same idea as cookie() as far as checking for the existance of a cookie and conditionally doing something with the stylesheet. I kind of liked your original cookie() function, never really thought of dynamically changing the stylesheet in use like that, before. ?
Copy linkTweet thisAlerts:
@Ness_du_FratauthorApr 23.2005 — Ok, I'm doomed.

Now, the page loads, blinks, and disappear... Arggghhh !!! I'll never get it...

With all the posts, I have no idea what I should put on the page exactly. Could you make a sump up for me ? What do I do ? drop the switchcss function ? Put the cookie() function in body onload ? ( it's this which makes the page disappear ).

Now, the switchcss isn't working anymore... I'm strating to get crazy over this page, since it's not even my single problem with it... Too bad there's no emoticon like a totally desperate looking one... ?
Copy linkTweet thisAlerts:
@gaston9x19Apr 23.2005 — lol man, that does sound pretty weird. Do you have MSN, AIM, or Yahoo? I'd be glad to try to come up with something that works right out of the box, but I'd like to make sure I understand exactly what you're trying to do. IM me sometime, if you would.

Ok, you've got an iframe, does the stylesheet need to change for that as well or just the main page? What actually initiates the change in your script? Have you tested how each stylesheet looks if you set them as the default one by one? Perhaps I could get a look at your current page, have a look at the source code? Thanks. ?
Copy linkTweet thisAlerts:
@Ness_du_FratauthorApr 23.2005 — I sent you a pm...

Actually, it's starting to work... execpt that the inner pages don't keep the main page's look when I come back. But the cookies work fine for the main page !!!

I might need your help, though.... A cookie thing for the inner pages as well would be great !!! :p
Copy linkTweet thisAlerts:
@Ness_du_FratauthorApr 23.2005 — SOLVED !!!! Thank you sooo much, gaston9x19 !!! ?
×

Success!

Help @Ness_du_Frat 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 6.3,
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: @meenaratha,
tipped: article
amount: 1000 SATS,

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

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...