Customizing styles: User-Controlled Style Sheets – Part III - Breaking the "changeStyle()" function into pieces
(Page 2 of 6 )
As you can see, the function is pretty similar to the previous version. However, we’ve added to it the handy capability to change both style sheets in a reversible way. In the first place, when the user clicks on the switcher link, the code grabs the corresponding style sheets, accessing them by their ID attribute, with the lines listed below:
// get style sheets
var defaultSheet=document.getElementById('default');
if(!defaultSheet){return;}
var newSheet=document.getElementById('accessible');
if(!newSheet){return;}
Once the style sheets have been accessed, the process of swapping them is extremely simple, as you’ll see in a moment. The function checks to see which style sheet is currently active. For whichever style sheet is enabled, the script simply disables it and activates the other one.
Otherwise, the reverse process occurs. If a particular style sheet is disabled, the code activates it again and disables its counterpart. The link is really working as a real reversible style switcher, but don’t forget that it’s changing entire style sheets. The reversible swapping process is performed with the following lines, assigning the corresponding Boolean values to each style sheet:
if(newSheet.disabled){
// disable previous active style sheet
defaultSheet.disabled=true;
newSheet.disabled=false;
}
else {
// enable new style sheet
newSheet.disabled=true;
defaultSheet.disabled=false;
}
Definitely, the function has been greatly improved. Happily, we’ve reached our first goal, which was to make the style change completely reversible for users. Finally, the function should be called when the document has been loaded, usually using the "onload" event handler:
// execute code when page is loaded
window.onload=function(){
if(document.getElementById){
changeStyle();
}
}
The main advantage of this method is that it is fairly straightforward. If you’re pretty familiar with DHTML, the approach is easy to follow.
So far, this version of the "changeStyle()" function isn’t very different from our earlier implementation, described in Part II of this article series. But just by adding a few lines of code, we’ve created a more powerful model, establishing the basics for further improvements.
Since we want to be kind and allow many Web developers to add new features to the current script, let’s show the full code for this approach. I will also include the proper style sheets used in the example.
Next: Listing the complete source code >>
More Style Sheets Articles
More By Alejandro Gervasio