12 replies [Last post]
westis
Offline
Regular
Last seen: 13 years 28 weeks ago
Timezone: GMT+1
Joined: 2005-07-02
Posts: 47
Points: 0

Hi,

I use the User Preference script and it works quiet nicely. But as I use it on several different pages on the same site there's one thing I haven't been able to solve.

When I move to another page the settings are correct, but all the select boxes move back to default, even when I use another setting.

Is there a way I can keep the select box at the chosen setting?

The site is at: http://www.oppnakanalen.se/vaxjo/default.asp

Thanks!

Tony
Tony's picture
Offline
Moderator
Brisbane
Last seen: 3 days 22 hours ago
Brisbane
Timezone: GMT+10
Joined: 2003-03-12
Posts: 5343
Points: 2964

User Preference Script: Select boxes change back to default

Hi westis,
Is there a way? Yes there is.

Is it easy? Not really.

What you would have to do is read from the cookie and set the correct form values to selected via JavaScript.

I will have a look into it, possibly today if everything else goes to plan.

westis
Offline
Regular
Last seen: 13 years 28 weeks ago
Timezone: GMT+1
Joined: 2005-07-02
Posts: 47
Points: 0

User Preference Script: Select boxes change back to default

Wonderful! Thanks!!

Tony
Tony's picture
Offline
Moderator
Brisbane
Last seen: 3 days 22 hours ago
Brisbane
Timezone: GMT+10
Joined: 2003-03-12
Posts: 5343
Points: 2964

User Preference Script: Select boxes change back to default

Hi westis,
You do realise part of the hidden handshake deal between us means you will be doing the testing Cool

This appears to work so far with my limited testing.
You just have to add these functions to the preferences.js file.

 
/* sets the selected value of each form element */ 
function setFormSelected(frmid, cookiename){ 
	var cookie=getCookie(cookiename); 						/* get existing cookie */ 
	var cookies=cookieCutter(cookie, "|");  
 
	var frm=document.getElementById(frmid); 
	if(testVar(frm)){ 
		var selects=frm.getElementsByTagName("SELECT"); 
		if(testVar(selects)){ 
			for(var sl=0; sl < selects.length; sl++){ 
				var opts=selects[sl].getElementsByTagName("OPTION"); 
				if(testVar(opts)){ 
					for(var op=0; op < opts.length; op++){ 
						if(findCookie( cookies, opts[op].value)){ 
							opts[op].selected="selected"; 
						} 
					} 
					 
				} 
			} 
		} 
	} 
} 
 
/*find the rule in the cookie */ 
function findCookie(cookies, fvalue){ 
	 
	var found = false; 
	 
	if(testVar(cookies)){ 
		for(var i=0; i < cookies.length; i++){ 
			var cookiecrumbs=cookies[i].split('?');			/* split cookie into selector and rule */	 
			if(testVar(cookiecrumbs[1])){ 
				chips=cookiecrumbs[1].split(":");  			/* split rule into property and value */ 
				vals=fvalue.split(":"); 
				if(chips[0]== vals[0] && chips[1] == vals[1]){			 
					found=true; 	 
				} 
			} 
		} 
	} 
	return found; 
} 

and at the bottom or where you call the onload event change it to
/* on page load read and set the cookie styles */ 
window.onload=function(){ 
	iceCookie('userpref', '|'); 
	setFormSelected('userpref', 'userpref');  
}

One problem I can see with this method is if you have for example color changing for the body and again in paragraphs, the wrong value may be displayed as selected.
I will have to think a little further on that one.
Let me know how it goes.

westis
Offline
Regular
Last seen: 13 years 28 weeks ago
Timezone: GMT+1
Joined: 2005-07-02
Posts: 47
Points: 0

User Preference Script: Select boxes change back to default

Deal! Laughing out loud

I added the new functions to preference.js. However, on the site I'm trying it on it doesn't work properly.

When I change for example the text color to blue and then move on to another page, the selected text color is shown as green and also the link color is shown as green although I have not changed it.

I also added a select box for theme that is changing several selectors and elements at the same time. When I change the theme on one page it's still shown as default on other pages, and also on the first page when I come back to that one.

I'm not very well-acquainted with JavaScript, so all I can do is to report how it's working on my site...

A minor problem I have, which is not urgent to solve, is that I'm not able to change the text color within <p> tags. Links in the <p> tag is changing fine. Also headings and <ul> in the same div (with id content, which is within the contentcontainer div, which in turn is within the container div) are changing color, as well as text that is not within <p> tags.

That line in preferences.js now looks like this:

"onchange='addstyle(\"body, div, #content, #content p, ul\",this.options[this.selectedIndex].value)'>"+

An example of a page that is not working (the code within the container div):

<div id="contentcontainer">

	<!-- The column to the right with sub-headings -->
	<div id="sidebar-a">

		    <h3 class="indrag">WEBB-TV</h3>
	<ul>
		<li><a href="webbtv.asp" id="nav2-webbtv">Se Öppna Kanalen Växjö via Internet</a></li>
	</ul>
		
		<div id="textbox">
		<script type="text/javascript">displayPreferenceControls();</script>
		<noscript>This would be user controls if you browser supported JavaScript</noscript>	
		</div>
       </div>



	<!-- Content -->
	<div id="content">
	
<h2>WEBB-TV</h2>
<p>H&auml;r kommer du att kunna titta p&aring; program som s&auml;nds i &Ouml;ppna Kanalen V&auml;xj&ouml;. Fr&auml;mst kommer det att handla om on-demand, allts&aring; att du kan titta p&aring; ett program n&auml;r du vill. Men vissa program kommer ocks&aring; att direkts&auml;ndas samtidigt b&aring;de i kabel-TV och h&auml;r p&aring; Internet.</p>

<p> </p>
<p>Snart kommer informationsfilmen om &Ouml;ppna Kanalen V&auml;xj&ouml; att l&auml;ggas ut h&auml;r!<br/>
</p>
	
	</div>


<!-- End of box for the two columns: the content and the sub-menu -->
</div>

If you're trying the user preferences on my site to see what I mean above, here's some translation from Swedish:

Tema = Theme
Textfärg = Text color
Textstorlek = Font size
Länkfärg = Link color
Återställ normalinställningarna = Clear cookie

Tony
Tony's picture
Offline
Moderator
Brisbane
Last seen: 3 days 22 hours ago
Brisbane
Timezone: GMT+10
Joined: 2003-03-12
Posts: 5343
Points: 2964

User Preference Script: Select boxes change back to default

Hi westis,
Yes that's the problem I was expecting.
Textfärg and länkfärg are both changing color so they are conflicting when trying to display the selected option.
Themes are also going to be a problem.
We will have to find another method.

Tony
Tony's picture
Offline
Moderator
Brisbane
Last seen: 3 days 22 hours ago
Brisbane
Timezone: GMT+10
Joined: 2003-03-12
Posts: 5343
Points: 2964

User Preference Script: Select boxes change back to default

Hi westis,
Looks like we are getting closer.
There are a lot of minor changes throughout so you would be best to replace all the functions and check very carefully through the displayControls and theme functions.

/************************************************************************************
Dynamic User Preference Script.
Copyright (C) 2005 Tony Aslett 
 
http://www.csscreator.com/
Version 1.6
updated: 22 July  2005

This script enables users with JavaScript and cookies enabled to select 
different styles to be applied to your site.
For more info see http://www.csscreator.com/generator/userpref.php

Please leave this notice at the top of the script.
-----------------------------------------------------------------------------------------------------------------------------
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details. http://www.gnu.org/copyleft/gpl.html
************************************************************************************/

/* This display the controls */
function displayControls(){
	/* Check if this will work before displaying controls */
	if(navigator.cookieEnabled && document.styleSheets && (document.styleSheets[0].addRule || document.styleSheets[0].insertRule)){
		document.write(
		"<form id='userpref' name='userpref'>"+
		
		" <label for='themea'>Theme:</label>"+
		"<select name='themea' id='themea' "+ 
		"onchange='theme(this.options[this.selectedIndex].value, this.id+\"_\"+this.selectedIndex)'>"+
		"<option value='clear' >Default</option>"+
		"<option value= 'camel' style='background-color:#FC9' >Camel</option>"+
		"<option value='mint' style='background-color:#0C6' >Mint</option>"+
		"<option value='aqua' style='background-color:#099' >Aqua</option>"+
		"<option value='blue' style='background-color:#06C'>Blue</option>"+
		"<option value='stark' style='background-color:#CCC'>Stark</option>"+
		"<option value='lavendar' style='background-color:#C9F'>Lavendar</option>"+
		"</select>"+
		
		" <label for='color'>Color:</label>"+
		"<select name='color' id='body' onchange='addstyle(\"body\",this.options[this.selectedIndex].value, this.id+\"_\"+this.selectedIndex)'>"+
		"<option value='color:clear' >Default</option>"+
		"<option value='color:#000' style='background-color:#000'>Black</option>"+
		"<option value='color:#00A'  style='background-color:#00A' >Blue</option>"+
		"<option value='color:green' style='background-color:green'>Green</option>"+
		"<option value='color:lime' style='background-color:lime'>Lime</option>"+
		"<option value='color:#800000' style='background-color:#800000'>Maroon</option>"+
		"<option value='color:#000080' style='background-color:#000080'>Navey</option>"+
		"<option value='color:teal' style='background-color:teal'>Teal</option>"+
		"<option value='color:#800080' style='background-color:#800080'>Purple</option>"+
		"<option value='color:#F00' style='background-color:#F00'>Red</option>"+
		"<option value='color:#FF0' style='background-color:#FF0'>Yellow</option>"+

		"</select>"+
		
	"</form>"+
		"<a href=\"#\" title=\"Clear your style cookie\" onclick=\"eatCookie('userpref')\">Clear Preference Cookie</a>"
		);
	}else{
		/* if their browser supports JavaScript but not some of the functions or cookies are disabled then you can output alternative content here.*/
		document.write('This should be user preference controls, but unfortunately your browser cannot understand the required functions');
	}
}	

/* This function  simplify changing multiple styles such as a theme */
function theme(thetheme, optidx){
	var borcolour;
	var bgcolour;
	var litcolour;

	switch (thetheme){
		case 'camel':
			borcolour='#C60';
			bgcolour='#FC9';
			litcolour='#FFC';
		break;
		case 'mint':
			borcolour='#063';
			bgcolour='#0C6';
			litcolour='#9FC';
		break;
		case 'aqua':
			/* ... */		
	}
	 
	addstyle("#rgh, .rgh, .whatsnew, .rghscroll, .rightbox, .forumline, .listdiv, .posttopic, .postfull, .postcont, .poster",  "border-color:"+borcolour+" !important", optidx); 
	addstyle("#lft, .box, .nonew, .new, .locked, .hot, .announce, .sticky, .blogging",  "border-color:"+borcolour+" !important", optidx); 
	
	addstyle("dl.forums, .mhead, .cats h3, .end, .topics", "border-bottom-color:"+borcolour+" !important" , optidx);
	addstyle("div .mhead",  "border-top-color:"+bgcolour+" !important" , optidx); 
	addstyle("#lft, .posttopic, .bstat, .nonew", "background-color:"+bgcolour+" !important", optidx);
	addstyle(".whatsnew", "background-color:"+borcolour+" !important", optidx);
	addstyle("body, .dl.forums dt, .mhead, .cats h3", "background-color:"+litcolour+" !important", optidx);
	

}

/* sets the selected value of each form element */
function setFormSelected(frmid, cookiename){
	var cookie=getCookie(cookiename); 						/* get existing cookie */
	var cookies=cookieCutter(cookie, "|"); 

	var frm=document.getElementById(frmid);
	if(testVar(frm)){
		var selects=frm.getElementsByTagName("SELECT");
		if(testVar(selects)){
			for(var sl=0; sl < selects.length; sl++){
			
				var opts=selects[sl].getElementsByTagName("OPTION");
				if(testVar(opts)){
					var oidx=findCookie(cookies, selects[sl].id);
					if(oidx){
						opts[oidx].selected="selected";
					}
						
				}
			}
		}
	}
}



/*pick cookie */
function findCookie(cookies, fid){
	
	var found = false;	
	if(testVar(cookies)){
		for(var i=0; i < cookies.length; i++){
			var cookiecrumbs=cookies[i].split('(');
			if(testVar(cookiecrumbs[1])){
				chips=cookiecrumbs[1].split("_"); 
				if(testVar(chips[0])){
					if(fid == chips[0]){
						found=parseInt(chips[1]);					
					}
				}
				
			}

		}
	}
	return found;
}



/* Set the style now and add it to a cookie for later */
function addstyle(selector, rule, optidx){
	var name;
	var cookie;
	var expdate;
	var property;
	var valu;
	optidx= "("+optidx+")";
	
	expdate=(24 * 60 * 60 * 1000 * 365);
	name='userpref';
	if(testVar(rule) && testVar(selector) ){
		valu=rule.split(":")[1];
		if(valu.indexOf("clear") >=0 ){
			property=rule.split(":")[0];
			cookie=biteCookie(name, selector, property, '|', optidx);
			if(testVar(cookie)){
				bakeCookie(name, cookie, expdate);
			}
			this.location.reload(false);	
		}else{
			setstyle(selector, rule); 
			addToCookieJar(name, selector, rule, '|', optidx);
		}
	}else{
		return false;
	}
}

/* removes one style from the cookie */
function biteCookie(name, selector, property, seperator, optidx){
	var sone;
	var stwo;
	var cookie;
	var cookies;
	var found;
	if(getCookie(name)){
		cookie=getCookie(name); 						/* get existing cookie */
		cookies=cookieCutter(cookie, seperator); 		/* get the cookies as an array */
		if(testVar(cookies)){
			for(var i=0; i < cookies.length; i++){
				cookiecrumbs=cookies[i].split('?');			/* split cookie into selector and rule */	
				if(testVar(cookiecrumbs[1])){
					chips=cookiecrumbs[1].split(":");  			/* split rule into property and value */
					if(chips[0]== property && cookiecrumbs[0] == selector){			
						found=i; 							/* Selector and property already exist */	
						cookies.splice( found, 1);
						cookie=cookies.join(seperator);	
						return cookie;						
					}
				}
			}
		}
		
		return cookie;
	}
	return false;
}

/* Set the style now and add it to a cookie for later of a full rule entered by user */
function anyRule(userRule){
	if(testVar(userRule)){
		userRule.slice(0,userRule.indexOf("}"));
		tokens=userRule.split("{");
		setstyle(tokens[0], tokens[1]); 
		addToCookieJar('userpref', tokens[0], tokens[1], '|', "()"  );
	}
}

/* Dynamically sets the selected style */
function setstyle(selector, rule){
	var rulecount;
	var fullrule;
	var ssheet;
	ssheet=(document.styleSheets.length==0)? document.createStyleSheet(): document.styleSheets[0];
	if( testVar(selector)  && testVar(rule) && rule.indexOf(":")  ){		
		if(ssheet.insertRule){	/* DOM */
			rulecount=ssheet.cssRules.length;
			fullrule=selector +"{"+ rule +"}";	
			ssheet.insertRule(fullrule, rulecount++ );
		}else if(document.styleSheets[0].addRule){ /* IE */
			rulecount=ssheet.rules.length;
			if(selector.indexOf(",") >0){
				selectors=selector.split(",");
				for(var s=0; s< selectors.length; s++){
					ssheet.addRule(selectors[s], rule, rulecount++);
				}
			}else{
				ssheet.addRule(selector, rule, rulecount++);	
			}
		}
		return true;
	}else{
		return false;
	}
}
/* test to see if a varable has an assigned value */
function testVar(objToTest) {
	return (objToTest == null || objToTest == undefined || objToTest == false)? false : true;
}

/* Store Cookie */
function bakeCookie(name, data, usebydate){
	var today=new Date();
	today.setTime(today.getTime() +usebydate);  
	usebydate=today.toGMTString();	
	document.cookie = name + "=" + escape(data)+ "; expires=" + usebydate +  "; path=/";
    //alert("Cookie length: "+data.length);
}

/* get the cookie and add style */
function iceCookie(name, seperator){
	if(navigator.cookieEnabled && document.styleSheets && (document.styleSheets[0].addRule || document.styleSheets[0].insertRule)){
		var vanilla;
		var crumbs;
		var opti;
		vanilla=getCookie(name);
		if(testVar(vanilla)){
			crumbs=cookieCutter(vanilla, seperator);
			for(var x=0; x< crumbs.length; x++){
				opti=crumbs[x].split("(");
				chips=opti[0].split("?");
				setstyle(chips[0],chips[1]);			
			}
		}
	}else{
		return false;
	}
}

/* get the full Cookie from the cookie jar*/
function getCookie(name) {
	var start;
	start=0;
	thisCookie = document.cookie.split("; ")
	for (i = 0; i < thisCookie.length; i++) {
		if (name == thisCookie[i].split("=")[0]) {
			chocchip=unescape(thisCookie[i].split("=")[1]);					
			return chocchip;
		}
	}
	return false;
}

/* break up the cookies */
function cookieCutter(cookie, seperator){
	return (testVar(cookie) && cookie.length >1 && cookie.indexOf(seperator) >0)? cookie.split(seperator): false;
}

function addToCookieJar(name, selector, rule, seperator, optidx){
	var found;
	var cookie;
	var cookies;
	var mix;
	var expdate;
	expdate=(24 * 60 * 60 * 1000 * 365);
	if(testVar(name) && testVar(selector) && testVar(rule) && testVar(seperator)){
		if(!getCookie(name)){
			bakeCookie(name, selector +"?"+rule, expdate); 	/* new cookie */
		}else{			
			cookie=biteCookie(name, selector, rule.split(":")[0], seperator);
			if(testVar(cookie)){
				mix=cookie+seperator+selector+"?"+rule+optidx;			
			}
			bakeCookie(name, mix, expdate); 				/*rewrite cookie */
		}
	}else{
		return false;
	}
}

/*Remove Cookies and refresh to clear styles */
function eatCookie(name){
	var yesterday=0-(24 * 60 * 60 * 1000)	
	bakeCookie(name, "", yesterday); 					/*remove cookie */
	this.location.reload(false);								/* reload to clear styles */
}

/* on page load read and set the cookie styles */
window.onload=function(){
	iceCookie('userpref', '|');
	setFormSelected('userpref', 'userpref'); 
}

westis
Offline
Regular
Last seen: 13 years 28 weeks ago
Timezone: GMT+1
Joined: 2005-07-02
Posts: 47
Points: 0

User Preference Script: Select boxes change back to default

Thanks for your great work, Tony! I'll try it on Sunday as I'll be away for a couple of days. Smile

Seems like I still have difficulties changing the colour of text within the <p> tag though... Currently I've commented out that part of the script on my site.

Tony
Tony's picture
Offline
Moderator
Brisbane
Last seen: 3 days 22 hours ago
Brisbane
Timezone: GMT+10
Joined: 2003-03-12
Posts: 5343
Points: 2964

User Preference Script: Select boxes change back to default

Hi Westis,
Have you tried using !important p{color:red !important;}[/code]

westis
Offline
Regular
Last seen: 13 years 28 weeks ago
Timezone: GMT+1
Joined: 2005-07-02
Posts: 47
Points: 0

User Preference Script: Select boxes change back to default

Now we're indeed getting closer! Just checked it now and it seems to work just fine!

Thanks also for the tip about adding !important, it made the trick!

Lots of thanks for sorting this out, Tony!!

westis
Offline
Regular
Last seen: 13 years 28 weeks ago
Timezone: GMT+1
Joined: 2005-07-02
Posts: 47
Points: 0

Background images not saved in cache?

For some reason it seems like background images are not saved in the cache... When I choose another theme the background images are changing. But as soon as I go to another page the background images are the default ones, although the rest of the theme changes remain.

Have a try at www.oppnakanalen.se/vaxjo

Tony
Tony's picture
Offline
Moderator
Brisbane
Last seen: 3 days 22 hours ago
Brisbane
Timezone: GMT+10
Joined: 2003-03-12
Posts: 5343
Points: 2964

User Preference Script: Select boxes change back to default

Hi westis,
Such a simple mistake Shock
I used "(" and ")" as separators which of course are used when changing background-images.

Anyway I have uploaded a newer version which you can access from the User Preference Page

The changes are just replacing "(" with "[" and ")" with "]"

In function findCookies var cookiecrumbs=cookies[i].split('[');

In function addstyle optidx= "["+optidx+"]";

In function anyRule addToCookieJar('userpref', tokens[0], tokens[1], '|', "[]" );

In function iceCookie opti=crumbs[x].split("[");

westis
Offline
Regular
Last seen: 13 years 28 weeks ago
Timezone: GMT+1
Joined: 2005-07-02
Posts: 47
Points: 0

User Preference Script: Select boxes change back to default

Thanks!! Now it's working!! Smile