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 to get this functionality to work

    How can I change the paragraph formatting in the SharePoint RichHtmlField

    How do I animate my CSS progress bar?

    How to Set an if in css for opera browser? [duplicate]

    How much media queries?

    How do I make buttons that have the same transitions and some of the same properties, but then also have some differing properties?

    How to change CSS to the same class but another input name

    How to vertically align image in a td cell, without vertically-align

    How to show indicator of loading?

    How to detect browser support for :after and :before

    How to select all fieldsets in a form except the first one?

    How to embed Javascript in CSS?

    How to align a link icon after the text via CSS?

    How can I vertically center this css/javascript based modal dialog?

    How to use a JQuery Show/Hide script, to show hidden text

    How to align lists to top right?

    How to turn off element CSS background when dragged

    How to center the Nav-Bar

    How can I convert this from jQuery to vanilla JS?

    how to setup capybara-webkit to test ajax calls and get screenshots(html with css and javascript loaded)

    How to apply a css class for jqGrid height property setGridHeight?

    jQuery or CSS - How do you make a link in a table row appear underlined even when the cursor is in a neighbouring cell?

    How to crop Google GeoChart and center its content?

    How to configure css flexbox so height of one of the block depends on it content?

    How to create invoice / money reciept with html [closed]

    Hide field on small viewport, click button to show again

    how to load a css for Safari only?

    How can I get my rows 100% wide?

    how to remove the last li::after for first line in specific width of an div

    how to make animated 404 gears?