How To Switch CSS Files On-The-Fly Using jQuery

This week’s Tutorial of the Week shows you how to switch CSS file using some simple jQuery. While CSS style sheet files are usually loaded on page load, there are occasions when we would want the CSS file to change or load dynamically, for instance, when changing the theme of a website.

Example Scenario

We have a multilingual website that offers 5 languages. Using a drop down menu, we can choose a new language to view. The new language strings are loaded dynamically via AJAX without the page reloading. Somehow, we need to find a way to load a different CSS file based on the language selected in a drop down menu without reloading the page.

For this particular example, we will assume that initially no CSS file is loaded. However, the moment a different language is loaded, we need our page to load the new CSS file.

The Solution

In order to trigger the file change or load, we need to create a JavaScript which is called when the change is needed. It’s important to keep in mind that the page cannot be refreshed.

When the function is triggered, our file should include the following code:

To do this, we can use the the following function:

function updateStyleSheet(filename) {

    // Create the CSS file name:

	newstylesheet = "style_" + filename + ".css";

    // Does the  tag (with id:dynamic_css) exist?
    // If not, we need to create it.

    if ($("#dynamic_css").length == 0) {

    	// The next line will add the
        //  tag between the
        // <head> tags.

        $("head").append("<link>")

        // The next line will select the
        //  element you just added.

        css = $("head").children(":last");

        // The next line will set the
        // attributes of the elements
        // to make it load the CSS file.

        css.attr({
          id: "dynamic_css",
          rel:  "stylesheet",
          type: "text/css",
          href: newstylesheet
        });

    // If the  element already exists, we
    // simply need to change the value of "href". 

    } else {
        $("#dynamic_css").attr("href",newstylesheet);
    }

}

The function dynamically creates a <link> tag with the dynamic_css ID and adds it right before the </head> tag.

What the code does

$("head").append("<link>");

… adds the tag. While…

css = $("head").children(":last");

… accesses that new tag.

The next time the language is changed, if the tag is already there, it is simply updated with the new style sheet url.

if ($("#dynamic_css").length == 0) {

That line checks whether the element with ID dynamic_css exists or not.

Summary

Here’s the code again with no comments:

function updateStyleSheet(filename) {

    newstylesheet = "style_" + filename + ".css";
    if ($("#dynamic_css").length == 0) {
    	$("head").append("<link>")
        css = $("head").children(":last");
        css.attr({
          id: "dynamic_css",
          rel:  "stylesheet",
          type: "text/css",
          href: newstylesheet
        });
    } else {
        $("#dynamic_css").attr("href",newstylesheet);
    }

}

To test this, you could easily create the following links:

Load English
Load Italian

Those two links should load style_english.css and style_italian.css respectively.

Go ahead and try this code – You will most likely need to alter it to suite your needs but the example above should help you get started.

Don't forget to check out more posts from the Tutorial of the Week section.

blog comments powered by Disqus
.