Cours Web

Réalisation de sites Internet Lausanne


Feuille de style CSS selon le visiteur

L'idée est de charger une feuille de style suivant un choix de l'utilisateur, puis de mémoriser ce choix dans un Cookie pour sa prochaine visite.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Document sans nom</title>
<script language="javascript" type="text/javascript">
<!--
function SetCookie (name, value) {
	var argv=SetCookie.arguments;
	var argc=SetCookie.arguments.length;
	var expires=(argc > 2) ? argv[2] : null;
	var path=(argc > 3) ? argv[3] : null;
	var domain=(argc > 4) ? argv[4] : null;
	var secure=(argc > 5) ? argv[5] : false;
	document.cookie=name+"="+escape(value)+
		((expires==null) ? "" : ("; expires="+expires.toGMTString()))+
		((path==null) ? "" : ("; path="+path))+
		((domain==null) ? "" : ("; domain="+domain))+
		((secure==true) ? "; secure" : "");
}

function getCookieVal(offset) {
	var endstr=document.cookie.indexOf (";", offset);
	if (endstr==-1)
      		endstr=document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name) {
	var arg=name+"=";
	var alen=arg.length;
	var clen=document.cookie.length;
	var i=0;
	while (i<clen) {
		var j=i+alen;
		if (document.cookie.substring(i, j)==arg)
                        return getCookieVal (j);
                i=document.cookie.indexOf(" ",i)+1;
                        if (i==0) break;}
	return null;
}


function test(feuille) {
	var pathname=location.pathname;
	var myDomain=pathname.substring(0,pathname.lastIndexOf('/')) +'/';
	var date_exp = new Date();
	date_exp.setTime(date_exp.getTime()+(365*24*3600*1000));
	// Ici on définit une durée de vie de 365 jours
	SetCookie("feuillecss",feuille,date_exp,myDomain);
	document.location.reload();
}

var feuille = GetCookie("feuillecss");
if(!feuille) feuille = 'bob';
document.write('<link rel="stylesheet" type="text/css" href="' + feuille + '.css">');
//-->
</script>

</head>

<body>

<h1 onclick="test('bob')">mettre bob</h1>
<h1 onclick="test('toto')">mettre toto</h1>
<h1 onclick="test('titi')">mettre titi</h1>

</body>
</html>