How to Use JavaScript to Change a Cascading Style Sheet (CSS) Dynamically

JavaScript Style Switcher for CSS


How to Use JavaScript to Change a Cascading Style Sheet (CSS) Dynamically

by Christopher Heng, thesitewizard.com

It may be useful sometimes to provide your visitors with the option to change the appearance of your website. Perhaps you want to provide theme support for your site. Or you may simply want to provide a bigger font size version of your site for older users who may not be able to read the small-sized text you use by default. This article describes how you can use JavaScript to dynamically change the cascading style sheets, or CSS, of your website.

Prerequisites

One of the assumptions I will make in this tutorial is that you know how to write HTML and CSS. You do not have to be highly proficient in either of these, but you should have at least a basic working knowledge. Some JavaScript knowledge is also necessary.

If you have not already done so, you may want to read the following articles as well. This guide was written as the part of a series of articles on how to provide alternate style sheets for your website and change them.

  1. How to Allow Your Visitors to Switch Between Alternate CSS Styles / Themes. It deals with the CSS aspect of switching style sheets.

  2. How to Use Cookies in JavaScript. Although not strictly part of the CSS style switcher series, the cookie management code provided in that article is used to preserve the theme selection that your visitors make on your site. Without setting a cookie, their CSS setting will not be retained when they go to the other pages on your website.

Steps to Adding a Style Sheet Switcher in JavaScript

Let's assume that you have the following style sheets defined in the HEAD section. This is the same code described and explained in the first instalment of this tutorial.

<link rel="stylesheet" type="text/css" title="blue" href="http://example.com/css/blue.css">
<link rel="alternate stylesheet" type="text/css" title="pink" href="http://example.com/css/pink.css">
  1. HTML Code to Provide a Way for Your Users to Choose the Style Sheet

    You will need to provide some way for your visitors to select the theme or CSS they want. There are many ways to do this, including the use of radio buttons, drop down selection boxes, normal submit buttons, text links, and so on. For usability reasons, you should not use things like checkboxes which suggests to users that they can simultaneously select a few themes and have them work together.

    Here's an example of HTML code using normal buttons.

    <button type="button" onclick="switch_style('blue');return false;" name="theme" value="Blue Theme" id="blue">Blue Theme</button>
    <button type="button" onclick="switch_style('pink');return false;" name="theme" value="Pink Theme" id="pink">Pink Theme</button>

    When the visitor clicks any of the buttons, the JavaScript onclick handler, switch_style(), will run. The function will be passed either 'blue' or 'pink' as its parameters, depending on which button is clicked. The words "blue" and "pink" correspond to the title attribute for the link elements referencing the style sheets.

  2. JavaScript Function to Change Style Sheets

    The actual JavaScript code needed to implement CSS style switching can be found below.

    Note that this script calls the set_cookie() and get_cookie() functions from the How to Use Cookies in JavaScript article. For your convenience, I have already included those functions in the block of code above, so you do not need to copy and paste from that article. However, you may still want to read the article to understand the default settings and assumptions I make in my cookie code.

    The switch_style() function essentially iterates through all your link tags looking for a style sheet with the same title as the text specified in its argument (parameter). If it matches, it sets a special property, called disabled, to false, thus enabling that style sheet. In the meantime, all other relevant style sheets are disabled. The function ignores all persistent style sheets as well as any non-style-sheet link tags, such as those used for your site's favicon.

    When it finishes, it sets a cookie with the necessary information about the style sheet setting. By default, the name of the cookie is "style" and it is retained for 30 days. You can change this by altering the values of the style_cookie_name and style_cookie_duration variables at the start of the script. You should also change the value of the style_domain variable to that of your own domain.

    To ensure that the visitors' style sheet settings remain when they visit other pages of your site, as well as when they reload the page, you will also need to add an onload attribute to your web pages' body tag. For example, change <body> to the following:

    <body onload="set_style_from_cookie()">

    This causes the browser to run the set_style_from_cookie() function when the page is loaded. The function merely checks for the style-setting cookie, and if present, switches the style sheets accordingly. Otherwise, it does nothing.

Demo

You can check out how the script works using the test copy loaded with this page. To change between the current style sheet used on thesitewizard.com and the older version, simply select the appropriate button below.

Note that the code used for this demo sets a cookie called "demo_theme" in your browser that is valid for only 1 day. The cookie will contain either the word "blue" or "grey", depending on which button you click. Your setting will only affect this page, and no other page on this site, since none of the other pages includes the style switcher JavaScript code.

In addition, the old grey theme does not support mobile browsers, since it pre-dated the era in which those phones were available.

Browser Compatibility

The above code has been tested in Firefox 2.x to 79.0, Vivaldi 1.6 (based on Chrome), IE 6 to 11, Opera 9.x to 12.17 and Safari for Windows 3.1. It should (hopefully) work for all other modern browsers as well.

Conclusion

This chapter concludes the series on creating a theme switcher, to change style sheets (or "skins" in layman's lingo), using both CSS and JavaScript.

Copyright © 2008-2024 by Christopher Heng. All rights reserved.
Get more free tips and articles like this, on web design, promotion, revenue and scripting, from https://www.thesitewizard.com/.

thesitewizard™ News Feed (RSS Site Feed)  Subscribe to thesitewizard.com newsfeed

Do you find this article useful? You can learn of new articles and scripts that are published on thesitewizard.com by subscribing to the RSS feed. Simply point your RSS feed reader or a browser that supports RSS feeds at https://www.thesitewizard.com/thesitewizard.xml. You can read more about how to subscribe to RSS site feeds from my RSS FAQ.

Please Do Not Reprint This Article

This article is copyrighted. Please do not reproduce or distribute this article in whole or part, in any form.

Related Pages

New Articles

How to Link to This Page

It will appear on your page as:

How to Use JavaScript to Change a Cascading Style Sheet (CSS) Dynamically





Home
Donate
Contact
Link to Us
No Spam Policy
Privacy Policy
Topics
Site Map

Getting Started
Web Design
Search Engines
Revenue Making
Domains
Web Hosting
Blogging
JavaScripts
PHP
Perl / CGI
HTML
CSS
.htaccess / Apache
Newsletters
General
Seasonal
Reviews
FAQs
Wizards

 

 
Free webmasters and programmers resources, scripts and tutorials
 
HowtoHaven.com: Free How-To Guides
 
Site Design Tips at thesitewizard.com
Find this site useful?
Please link to us.