Customizing styles: User-Controlled Style Sheets - Part II - Listing full source code
(Page 3 of 4 )
As I promised before, if you wish to implement this initial approach in your Web application and add your own improvements, here's the full code for changing style sheets:
<html>
<head>
<title>CHANGING STYLES BY STYLE SHEET</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="default.css" id="default" />
<link rel="stylesheet" type="text/css" href="accessible.css" id="accessible" />
<script language="javascript">
// disable accessible style sheet
var accessibleSheet=document.getElementById('accessible');
accessibleSheet.disabled=true;
changeStyle=function(){
var switcher=document.getElementById('switcher');
switcher.onclick=function(){
var defaultSheet=document.getElementById('default');
if(!defaultSheet){return;}
// disable default style sheet
defaultSheet.disabled=true;
var newSheet=document.getElementById('accessible');
if(!newSheet){return;}
// enable accessible style sheet
newSheet.disabled=false;
return false;
}
}
// execute function when page is loaded
window.onload=function(){
if(document.getElementById){
changeStyle();
}
}
</script>
</head>
<body>
<h1>Page Name</h1>
<p><a href="#" title="Change Style" id="switcher">Change style</a></p>
<div class="content">
<p>Content for div1 goes here...Content for div1 goes here...Content for div1 goes here...</p>
</div>
<div class="content">
<p>Content for div2 goes here...Content for div2 goes here...Content for div2 goes here...</p>
</div>
<div class="content">
<p>Content for div3 goes here...Content for div3 goes here...Content for div3 goes here...</p>
</div>
</body>
</html>
Taking a look at the full source code, it's becomes clear that once both style sheets have been defined, the first two lines of JavaScript code deactivate the "accessible" style sheet, making "default.css" the unique active style sheet in the document.
Then, with a single style sheet to deal with, the "changeStyle()" function is executed after the document has been loaded. Finally, when the user clicks on the switcher link, style sheets are changed gracefully.
From the previous lines, it's easy to deduce that specifying different rules for the same "content" CSS class applied to the <div> elements, and defined in both style sheets, can achieve a dramatic style change with minimum of effort. With a little bit of JavaScript code, we're switching style sheets on and off. Definitely, we have improved our background about style changes.
Next: Summary and further reading >>
More Style Sheets Articles
More By Alejandro Gervasio