So in part one of this post we got all the CSS and other theme file we needed to stuck them in a document library.
This line of code basically finds all the linked CSS files in the page and changes thier value to point to the new style sheet you select. This is fine on a site that just uses one CSS file but in SharePoint bad things happen. In most cases we dont want to completely remove the reference to core.css. For most themes many elements don’t need to be changed so we only have to write the CSS to change them and let core.css do the rest. If you remove core.css its like using a global reset (discussed in more detail here) which means you will have to restyle everything. So them point is we want to leave core.css in the page and just add our theme.
To do this I had to make some changes to the master page to create to interface users will use to swap themes.
Edit the Masterpage
Here is the code I added to the masterpage. This can be styled to look however you want and can be added anywhere in the page that makes sense.[sourcecode language=”html”]
In addition to this we also need to add a link to our css file to the master page. I put it at the end of the head section.[sourcecode language=”html”] [/sourcecode]
I added a class to the link so that we can use jQuery to target only that css link and change it to match the theme the user selects. Initially I left the href value blank but if you want to apply some default styles you would just add the link to the css file there.
Use jQuery to Swap the CSS
- You will need jQuery either locally or linked from Google. Just update the link on line 1 as needed.
- In the code above you will notice a link to cookie.js, this is the jQjuery cookie plugin that you will need in order to save users’ theme selections. In the code above on line 13 you will see where I create a cookie named css. For testing purposes you can uncomment line 10 to see what the cookie value is on page load. You can download the plugin from here. jQuery Cookie Plugin
- You can see the original code I started from in this script from CSS Newbie
While this is a very simple solution it is a quick way to add in some fuctionality that many users want without alot of custom code or requiring the user to navigate to multiple pages. Users like to feel that they have some control over the site (even if its just changing the color). Feel free to post any questions or comments.