User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the JavaScript / DHTML / AJAX section within the Web Development category of DaniWeb, a massive community of 428,373 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 3,522 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our JavaScript / DHTML / AJAX advertiser: Lunarpages Web Hosting
Views: 651 | Replies: 0
Reply
Join Date: Oct 2005
Posts: 236
Reputation: Inny is an unknown quantity at this point 
Rep Power: 4
Solved Threads: 5
Inny's Avatar
Inny Inny is offline Offline
Posting Whiz in Training

css cookie issue

  #1  
Jun 1st, 2008
Im using A css rule selection script to change background images. It works but theres an annoying problem.
when the user sets the image they want, its changed instantly (dynamically written to the existing stylesheet), however when you reload the page the default background image is shown (the one actually permanantly written in the stylesheet) until the page has completed loading, then the cookie kicks in and the users prefrence is shown.

Is there some way to prevent this happening, so that after selecting an image, it stays without disruption when the page is reloaded? Would this have to physically document write/change the existing stylesheet?

[inlinecode]
/* This display the controls */
function displayPreferenceControls(){
	/* 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'>"+
		"<fieldset>"+
		"<legend>Controlled Choices</legend>"+
		" <label for='background-image'>background-image:</label>"+
		"<select name='background-image' id='background-image' onchange='addstyle(\"body\",this.options[this.selectedIndex].value, this.id+\"_\"+this.selectedIndex)'>"+
		"<option value='background-image:url(http://i14.photobucket.com/albums/a345/Instar/greenbgfade17oi.jpg)' >Default</option>"+
		"<option value= 'background-image:url(http://i14.photobucket.com/albums/a345/Instar/Avatars/temp_6ee79edc8b98e534671149f81b0f16.jpg)'  style='forest' >forest</option>"+
		"<option value='background-image:url(http://i14.photobucket.com/albums/a345/Instar/Avatars/try2.jpg)' style='python2'>Python2</option>"+
		"<option value='background-image:url(http://i14.photobucket.com/albums/a345/Instar/HornedLizard-1.jpg)' style='lizard1'>lizard1</option>"+
		"<option value='background-image:url(http://i14.photobucket.com/albums/a345/Instar/reptile_003-1.jpg)' style='lizard2'>lizard2</option>"+
            "<option value='background-image:url(http://i14.photobucket.com/albums/a345/Instar/screenys/5810779220_522928.jpg)' style='monitors'>monitors</option>"+
            "<option value='background-image:url(http://i14.photobucket.com/albums/a345/Instar/wheelerii.jpg)' style='Gecko'>Gecko</option>"+

		"</select>"+
		
		"</form>"+
	
		"<a href=\"#\" onclick=\"eatCookie('userpref')\">Clear 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');
	}
}	

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

	var frm=document.getElementById(SELECT);
	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";
					}
						
				}
			}
		}
	}
}


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'); 
}
[/inline code]

<script type="text/javascript">displayPreferenceControls();</script>
Last edited by Inny : Jun 1st, 2008 at 1:45 pm.
Always carry a flagon of whiskey in case of snakebite and furthermore always carry a small snake.
W. C. Fields
AddThis Social Bookmark Button
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

DaniWeb JavaScript / DHTML / AJAX Marketplace
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

Thread Tools Display Modes

Other Threads in the JavaScript / DHTML / AJAX Forum

All times are GMT -4. The time now is 7:00 am.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC