views:

75

answers:

4

Is it possible to have 3-4 CSS on a page, and then on any event, say click, change the css for entire webpage. This way we can give our user the ability to change the theme. I know we can change the css of an element by:

$("#myElementID").removeClass("class1").addClass("class2");
+2  A: 

The CSS Zen Garden (see the fifth question) ended up deciding that the easiest way was just to refresh the page and set a new CSS server side.

Turtle
But i want to do this @client side, i mean using jQuery or javascript
Rakesh Juyal
+4  A: 

Yes, it is possible. Typically what you would do is write a JavaScript function that will change, or add, or remove a style sheet from the <head> of the document. To make the experience a little better you'll typically store the user's preference in a cookie. There's an article on A List Apart that show how to implement this.

And of course, you can do this with jQuery... you may want to check out the source of jStyler.

Zack Mulgrew
this seems promising :) +1
Rakesh Juyal
See the jStyler plguin for jQuery, the source is pretty short and easy to understand.
Zack Mulgrew
A: 

CSS is emdeded to DOM over 'link' tag, so you can locate this link and add/remove

Following code shows how to remove and add new one (I'm using MS AJAX see method $get, but you can replace it with pure DOM or other dialect):

    var head = document.getElementsByTagName('head')[0];

    var oldLink = $get("nameOfLink", head);
    if(oldLink!=null) 
        head.removeChild(oldLink); //remove old entry
    var s = document.createElement('link');
    s.id="nameOfLink";
    s.type = 'text/css';
    s.rel="stylesheet";
    s.charset ='utf-8';
    s.href = "http://your-provided-url";
    head.appendChild(s);
Dewfy
does removing and adding the `link rel="stylesheet"` will do this? not sure, but i will have to give it a try
Rakesh Juyal
@Rakesh Juyal you mean redundancy of type/id/charset? If so then charset is really redundant, but type is strongly recommended by some browsers (May be I'm wrong about kind, but IE needs it). At last 'id' is needed by script logic.
Dewfy
A: 

Usually best to load an external stylesheet (append a <link>): http://snipplr.com/view/3873/failsafe-load-for-attaching-stylesheet/

But if you need to create a bunch of styles on the fly, you can also build and append a <style> node to the DOM: http://jonraasch.com/blog/javascript-style-node

Jon Raasch