How do I switch external CSS files?


Tags: javascript,jquery,css,ajax

Problem :

I've got a couple books that I'm reading on AJAX, but still quite new. All the tutorials and these books have the ubiquitous examples of: an auto-populating search bar and an asynchronous form validator. Those are both great, but not what I'm looking for. Specifically, I want to click a button and switch the external CSS file in my header include. Is this possible? Well... I know it's possible, but how do you do it?

PS: I have jQuery in this project, so if there is something built in from there, even better!

PPS: I'm realizing I have not included important information (don't shoot me!):

  1. The final goal of this will be to have a user settings section where the user can click a radio button and decide the color scheme they want to use for our app. So we will eventually have something like 8 different CSS styles to choose from. Not sure if this will alter the best method to achieve this.

  2. The user is logging into their account and changing their setting there. I want their changes to 'stick' until they decide to change the stylesheet again. I can do this manually in MySQL as we have a table called stylesheets with the various user stylesheets numbered... so in actuality, what I'm needing to do is change that MySQL value asynchronously so the CSS is immediately loaded.



Solution :

Stylesheet Switcher in jQuery.

In response to the 'newbie followup' comment, I will try to make it a little more instructional.

The page I was playing with to test on while writing can be found here.

Page Display

You're going to want to have your current stylesheet displayed in a <link> tag in the <head> of each of your pages. The <link> tag will need an id for reference later in JavaScript. Something like:

<?php 
  // Somewhere in the server side code, $current_stylesheet is read from the user's 
  // "preferences" - most likely from a database / session object
  $current_stylesheet = $user->stylesheet;
?>
<link href='<?php echo $current_stylesheet ?>' rel='stylesheet' type='text/css' id='stylelink' />

Changing the preference

Once you are displaying the users stylesheet, you need a way to change it. Create a <form> that will send a request to the server when the user changes their stylesheet:

<form method="GET" id="style_form" >
  <select name="stylesheet" id="styleswitch">
    <option value="css1.css">Black &amp; White</option>
    <option value="css2.css" selected="selected">Shades of Grey</option>
   </select>
   <input value='save' type='submit' />
</form>

Server Side

Now, without jQuery, submitting this form should GET (you could change it to POST if you like) stylesheet={new stylesheet} on the current page. So somewhere in your bootstrap / sitewide include file, you do a check for it, a php sample:

$styles = array(
  'css1.css' => 'Black &amp; White',
  'css2.css' => 'Shades of Grey',
);

if (!empty($_GET["sytlesheet"]) {
  // VALIDATE IT IS A VALID STYLESHEET - VERY IMPORTANT
  // $styles is the array of styles:
  if (array_key_exists($_GET["stylesheet"], $styles)) {
    $user->stylesheet = $_GET["stylesheet"];
    $user->save();
  }
}

Live Preview

At this point, you have a functioning styleswitcher for the lame people without javascript. Now you can add some jQuery to make this all happen a little more elegantly. You'll want to use the jQuery Form Plugin to make a nice ajaxForm() function, that will handle submitting the form. Add the jQuery and jQuery Form library to the page:

<script type='text/javascript' src='/js/jquery.js'></script>
<script type='text/javascript' src='/js/jquery.form.js'></script>

Now that we have the libraries included -

$(function() {
  // When everything has loaded - this function will execute:


  $("#style_form").ajaxForm(function() {
    // the style form will be submitted using ajax, when it succeeds:
    // this function is called:
    $("#thediv").text('Now Using: '+$('#styleswitch').val());
  });

  $("#styleswitch").change(function() {
    // When the styleswitch option changes, switch the style's href to preview
    $("#stylelink").attr('href', $(this).val());
    // We also want to submit the form to the server (will use our ajax)
    $(this).closest('form').submit();
  });

  // now that you have made changing the select option submit the form,
  // lets get rid of the submit button
  $("#style_form input[type=submit]").remove();
});

    CSS Howto..

    How can I delete unused css lines?

    How to have logo go into / overlay black bar along the top of screen?

    How to make a correct mosaic with CSS?

    How to style form elements unobtrusively with JavaScript and CSS?

    How can I add a footer to my website similar to the header?

    How to vertically center a div for all browsers?

    How can I automatically highlight a specific character in link text using JQuery + CSS?

    Getting an class to show when item is clicked

    Show dropdown menu only when hovered on span in li

    How to align text and images on one line and position those to the left and/or right?

    Why do menu bullets show up on my menus?

    custom styles not effecting the nested accordion jquery - How to fix

    How to Set all children start with same line of main parent

    How to properly center a 100% width div in css

    how to fix closure compiler error on css({ float: 'left' }) [duplicate]

    How do I center align the items in my menu?

    How to rotate the background image in css?

    CSS How to change 3 line (menu icon) color when hover

    How to dynamically change width of Div1 inside a scrollable Div2 to Div2's width

    How can I override an external css?

    How to get equal height for all sections?

    How to add conditional formatting to list items in CSS

    How to make multiple breaks using CSS?

    how to layout tictactoe with html and css on a webpage

    How to center image which is bigger than screen?

    How do I override a css value?

    How to change the css style for phone and desktop?

    How can I convert a SASS file to a CSS file in an ANT task?

    CSS positioning: how to make it relative to one element but not the other?

    How to add a .css to a .cshtml