Change Page Color Scheme Dynamically using Javascript

Share this Article :


Now, get it into technical

I presume that You have your css ready with you. Here is your Dropdown box code by which user will make a selection of His choice. Name the Option values same as the CSS file names with out extension .css

 
<select name="changescheme" id="changescheme" onchange="changeTheme()">
<option value="orange">Orange</option>
<option value="yellow">Yellow</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
</select>

Demo :

To attain this functionality We will use four javascript functions

1.loadTheme
2.changeTheme
3. setCookie
4.getCookie

First Two functions used to load the theme on page load and dynamically changes theme when user is wiling to

the second two functions used to retain the selection of the user across the pages ..

Here are functions in detail

//  Setting  Cookie  
function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}
 
// Get  value  stored in Cookie 
function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}
 
//  This function will fire on body load
function  loadTheme()
{
		var c_val=getCookie("colorscheme");
		if (c_val!="")
		document.getElementById("pagestyle").href=c_val+'.css';
 
}
// This  call  ensures  to load  the Previously selected color Scheme by User
loadTheme();
 
//  This function will fire on change of Dropdown
function  changeTheme()
{
		var c_val=document.getElementById("changescheme").value;
		document.getElementById("pagestyle").href=c_val+'.css';
		setCookie("colorscheme",c_val,30);
 
}

Pages: 1 2 3

Written by adrevol

{adrevol has written 91 posts on ITTreats.com . See all posts by }


Leave a Reply