Wednesday, October 31, 2007

jquery plugin : switchcss

Introduction



I was answering a question posed on the CodeIgniter forum about a stylesheet switcher and i came up with this code. It is rough but it worked.

Later that day i read in the mailinglist of jquery there was A Plugin Development Pattern tutorial

After reading this i wanted to make the rough code into a plugin and switchcss was born.

Features



Other stylesheet switchers i found where based on alternative stylesheets that had to be loaded and thus making the pages heavier to load. This was the concern of the poster on the CodeIgniter forum so i made this stylesheet switcher to work with one theme css that gets changed.

It remembers the chosen theme using a cookie.

Files



Dependencies:


switchcss plugin

Usage



Link to the files and at least one theme css file and add following code to your ready method

$(function(){
// previously chosen theme
$.cookieswitchcss();
// elements that hold the alternate themes
$('.switchcss').switchcss();
});

Now clicking on the elements changes the stylesheet and adds the theme to the cookie.

By default the css filename is prefixed with theme_ and the text of the element is extracted to add to the prefix of the name. And the link element should have the title themecss.

All the defaults :

cookiename

default : csstheme

linktitle

the value of the title attribute from the link element that holds the theme css file.

default : themecss

cssprefix

general prefix used by the theme css files

default : theme_

themename

Which value to use to complete the css file name.

text : content of the element

other : value of the attribute you define here

default : text



These options are used by the two functions so i made them public (thank you tutorial) so you only have to define them once.


$.fn.switchcss.defaults.linktitle = 'theme';
// gets the value of the title attribute of the anchors
$.fn.switchcss.defaults.themename = 'title';
$.cookieswitchcss();
$('a').switchcss();


I hope it comes in handy for someone.

1 comment:

Anonymous said...

Thats very nice, ill use it with my apps and future websites ill develop =D

Thanks for the plugin.