Introducing DynamicStyle.js – modify arbitrary global CSS

While working on a project for school, I discovered that there was no easy way to add, modify, and remove global CSS. There are three well-known ways of dynamically modifying the CSS in a page: 1) Set the style of individual named elements, 2) set the class of the <body> element to invoke CSS predefined for the circumstance, or 3) add or remove links to existing stylesheets. None of these address the issue of adding arbitrary global CSS at an arbitrary time.

After several attempts (including modifying the contents of a text node inside a <style> node), I found a working solution using data: protocol URLs in <link> nodes. Here, for your coding pleasure, is DynamicStyle-0.4.js:

The DynamicStyle library is ridiculously easy to use, since initialization and cleanup are handled automatically. Here are some sample calls to the DynamicStyle library:

DynamicStyle.setStyle('search-hilite', 'span.search-1 { background-color: yellow; }');
DynamicStyle.getStyle('search-hilite');
DynamicStyle.removeStyle('search-hilite');

The code is available under both the Creative Commons Attribution Share-Alike license and the GPL.


Newer versions and changelog

(This was originally a separate page on the site; I moved it here in 2020 to archive it.)

This javascript "library" (more of a helper) implements an on-the-fly global style manager. Scripts can add, modify, retrieve, and remove snippets of CSS that are applied globally, with very little overhead. Example calls:

DynamicStyle.setStyle('search-hilite', 'span.search-1 { background-color: yellow; }');
DynamicStyle.getStyle('search-hilite');
DynamicStyle.removeStyle('search-hilite');

Download the current version (0.5). (Depends on JQuery, but only for initialization.)

Specification

DynamicStyle.js exposes three public API calls:

DynamicStyle.setStyle(handle, snippet)
Add or update the dynamic stylesheet with the handle "handle".
DynamicStyle.getStyle(handle)
Retrieve the contents of the dynamic stylesheet with the handle "handle".
DynamicStyle.removeStyle(handle)
Destroy the dynamic stylesheet with the handle "handle".

The library uses data: URLs to simulate external stylesheets.

Future work

None currently planned.

Change log

Version 0.5

Released on 2007-1-21, version 0.5 [.js format] changes dependency from Prototype.js to JQuery.js.

Version 0.4

Released on 2006-9-27, version 0.4 [.js format] is the first public version. Provides the following API calls:

DynamicStyle.setStyle(handle, snippet)
Add or update the dynamic stylesheet with the handle "handle".
DynamicStyle.getStyle(handle)
Retrieve the contents of the dynamic stylesheet with the handle "handle".
DynamicStyle.removeStyle(handle)
Destroy the dynamic stylesheet with the handle "handle".

The library uses data: URLs to simulate external stylesheets.

Requires the Prototype.js library.


No comments yet. Feed icon