Created by: gwideman, Sep 21, 2010 9:40 pm
Revised by: gwideman, Nov 8, 2011 9:19 pm (16 revisions)

Overview

Demonstrates using Javascript in a Widget to load a CSS file.
  • Store a CSS file on wikispaces.
    • Typical file address: /file/view/gwtest.css/164469469/gwtest.css
    • Short version also works: /file/view/gwtest.css, and avoids serial number that changes as you upload new versions.
  • Add a script (in an Other HTML widget) to load that CSS file in the document ready event.
  • Possibly add the script to the navigation page (space.menu) so that it runs for all pages.

Benefits

  • Allows use of CSS even when the Custom CSS feature is not available
  • Compared to using Javascript to add to the CSS rules directly, this method is likely more cross-browser friendly?

Shortcomings

  • Editing the CSS file is more tedious than the official Custom CSS feature.

Code:

<script type="text/javascript">
jQuery(document).ready(function() {
  var cssPath = '/file/view/gwtest.css';
  var cssNode = document.createElement('link');
  cssNode.type = 'text/css';
  cssNode.rel = 'stylesheet';
  cssNode.href = cssPath;
  cssNode.media = 'screen';
  cssNode.title = 'dynamicLoadedSheet';
  document.getElementsByTagName("head")[0].appendChild(cssNode);
} );
</script>
(From: http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS)
The particular CSS file:
.wikiBox h2 {
 color:#ff8800;
}
... and here's some sample text to demo the orange H2:

H1 heading

H2 heading: this should be orange, due to CSS loaded by javascript

H3 heading

And some regular text

Widget with JS is inserted below (visible when editing only):