styleswitcher.js by Paul Sowden


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function setActiveStyleSheet(title) {
  2. var i, a, main;
  3. for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
  4. if(a.getAttribute("rel") && a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
  5. a.disabled = true;
  6. if(a.getAttribute("title") == title) a.disabled = false;
  7. }
  8. }
  9. }
  10.  
  11. function getActiveStyleSheet() {
  12. var i, a;
  13. for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
  14. if(a.getAttribute("rel") && a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  15. }
  16. return null;
  17. }
  18.  
  19. function getPreferredStyleSheet() {
  20. var i, a;
  21. for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
  22. if(a.getAttribute("rel") && a.getAttribute("rel").indexOf("style") != -1
  23. && a.getAttribute("rel").indexOf("alt") == -1
  24. && a.getAttribute("title")
  25. ) return a.getAttribute("title");
  26. }
  27. return null;
  28. }
  29.  
  30. function createCookie(name,value,days) {
  31. if (days) {
  32. var date = new Date();
  33. date.setTime(date.getTime()+(days*24*60*60*1000));
  34. var expires = "; expires="+date.toGMTString();
  35. }
  36. else expires = "";
  37. document.cookie = name+"="+value+expires+"; path=/";
  38. }
  39.  
  40. function readCookie(name) {
  41. var nameEQ = name + "=";
  42. var ca = document.cookie.split(';');
  43. for(var i=0;i < ca.length;i++) {
  44. var c = ca[i];
  45. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  46. if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  47. }
  48. return null;
  49. }
  50.  
  51. window.onload = function(e) {
  52. var cookie = readCookie("style");
  53. var title = cookie ? cookie : getPreferredStyleSheet();
  54. setActiveStyleSheet(title);
  55. }
  56.  
  57. window.onunload = function(e) {
  58. var title = getActiveStyleSheet();
  59. createCookie("style", title, 365);
  60. }
  61.  
  62. var cookie = readCookie("style");
  63. var title = cookie ? cookie : getPreferredStyleSheet();
  64. setActiveStyleSheet(title);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.