0

I'm using this HTML code:

<head>

<link href="defualt.css" rel="stylesheet" type="text/css" />
<link href="theme1.css" title="theme1" rel="alternate stylesheet" type="text/css" />
<link href="theme2.css" title="theme2" rel="alternate stylesheet" type="text/css" />
<link href="theme3.css" title="theme3" rel="alternate stylesheet" type="text/css"  />

<script type="text/javascript" src="javascript.js"></script>

</head>
<body>

<form>
    <select id="myList" >
        <option value="default">Default</option>
        <option value="theme1">Theme 1</option>
        <option value="theme2">Theme 2</option>  
        <option value="theme3">Theme 3</option>
    </select>
</form>

</body>

It's a form to change style sheets. This is the javascript I'm using:

function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  } 
  createCookie("style", title, 7);
}

function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

window.onload = function(e) {
  var cookie = readCookie("style");
  var title = cookie ? cookie : getPreferredStyleSheet();
  setActiveStyleSheet(title);
}

var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);


function initate()
{

document.getElementById("myList").onchange = function() {
   setActiveStyleSheet(this.value);
   return false
};

}

window.onload = initate;

The changing of the style sheets work great but I want the option chosen in the menu to stay after I reload the page. This works as it should in Firefox but not in Chrome. I'm quite new to javascripts and I haven't written all of this code myself so I don't fully understand all of it. Is it possible to save the chosen option of the menu in the same cookie or is it better/easier to create a new one?

Benji
  • 615
  • 5
  • 11
  • 25

1 Answers1

1

If you're reloading the page, there is nothing you can do to persist the state of the drop down selection within the page (HTML, Javascript) itself. I would suggest you use a cookie to store the current selection, read in the value on page load, and set the option in the drop down accordingly.

For cookie JS, see: http://www.quirksmode.org/js/cookies.html

function initate() {
    window.selectBox = document.getElementById("myList");
    var cookie = readCookie("style");
    var title = cookie ? cookie : getPreferredStyleSheet();
    setActiveStyleSheet(title);
    getTheme();
    selectBox.onchange = function () {
        setActiveStyleSheet(this.value);
        setTheme();
    };
}
window.onload = initate;

function setActiveStyleSheet(title) {
    var i, a, main;
    for (i = 0; (a = document.getElementsByTagName("link")[i]) ; i++) {
        if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
            a.disabled = true;
            if (a.getAttribute("title") == title) a.disabled = false;
        }
    }
    createCookie("style", title, 7);
}

function getActiveStyleSheet() {
    var i, a;
    for (i = 0; (a = document.getElementsByTagName("link")[i]) ; i++) {
        if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
    }
}

function getPreferredStyleSheet() {
    var i, a;
    for (i = 0; (a = document.getElementsByTagName("link")[i]) ; i++) {
        if (a.getAttribute("rel").indexOf("style") != -1
           && a.getAttribute("rel").indexOf("alt") == -1
           && a.getAttribute("title")
           ) return a.getAttribute("title");
    }
}

function getTheme() {
    var storedThemeVal = readCookie('selectedTheme');
    if (storedThemeVal != null && storedThemeVal != "") {
        for (var i = 0; i < selectBox.options.length; i++) {
            if (selectBox.options[i].value == storedThemeVal) {
                selectBox.selectedIndex = i;
            }
        }
    }
}

function setTheme() {
    var selectedThemeVal = selectBox.options[selectBox.selectedIndex].value;
    createCookie('selectedTheme', selectedThemeVal);
}

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

Note that Chrome does not support local cookies by default (file:// protocol). Either test this in a server environment, or enable file cookies by adding --enable-file-cookies to your shortcut to Chrome (so, if you have a shortcut, right click on it, click properties and edit the Target to include --enable-file-cookies at the very end, after the quotes).

Alternatively, you could also modify the URL (user a query string parameter) to store/read the current selection (similar to above). However, this of course would be lost if the user leaves the site and comes back to it.

Adding a parameter to the URL with JavaScript

Community
  • 1
  • 1
matthewpavkov
  • 2,918
  • 4
  • 21
  • 37
  • The state of inputs in a form can be "stored" by the browser. This would be a browser-specific thing. I would not rely on this. So, for instance, you may enter text into a text input, or make a selection in a drop down, refresh the browser, and the text/selection remains. However, as I said, you cannot (and should not) rely on this. – matthewpavkov Jan 15 '13 at 15:02
  • And how could I write a cookie to solve this problem? I don't know how to do this since I already have cookies on the site. – Benji Jan 15 '13 at 15:15
  • I already have the code to create the cookie in my javascript, I'm just not sure how to call the function correctly to get it to save my chosen option in the dropdown menu and then read it as well. Can it be saved in the same cookie as the chosen theme? – Benji Jan 15 '13 at 15:32
  • Ok, check my updated answer above. This would be much easier using jQuery, FYI. – matthewpavkov Jan 15 '13 at 16:03
  • Yes, it seems to be what I want but I can't figure out what to write to call it properly. I figure it's suppose to be something similar like the one I have, `document.getElementById("myList").onchange = function() { setActiveStyleSheet(this.value); return false };` but I can't get anything to work. – Benji Jan 15 '13 at 16:31
  • Oh, and I removed the `function readCookie` and `function createCookie` since I already have them since before. Or did you include them because I need to place everything in a certain order? Or do I need to keep duplicates of the code? – Benji Jan 15 '13 at 16:34
  • No, your cookie functions will work. I removed them from my code example. – matthewpavkov Jan 15 '13 at 16:48
  • And the code to manage to get everything to work? Mind helping me with that part as well? – Benji Jan 15 '13 at 16:55
  • Ok, what I provided should get you very close to a working solution. – matthewpavkov Jan 15 '13 at 17:14
  • While doing like that nothing works for me. Not the style sheet changer nor keeping the right option in the drop down menu. And no cookie is being created either. – Benji Jan 15 '13 at 17:29
  • It is still not working at all. Same as before that none of the style sheets changing, no cookies being created or the option in the menu being correct :( – Benji Jan 15 '13 at 18:21
  • I love you man! It's finally finally finally working! Thank you so much for your awesome efforts :) – Benji Jan 15 '13 at 19:38