March 14, 2012
Styling using Javascript Cookie
Question by Tim D'Haene
I seem to be able to retrieve the value of the cookie but the style of the corresponding ID isn’t changed. What am I missing?
function getCookie(name) {
var cookieName = document.cookie;
var prefix = name + "=";
var begin = cookieName.indexOf("; " + prefix);
if (begin == -1) {
begin = cookieName.indexOf(prefix);
if (begin != 0) return null;
} else begin += 2;
var end = cookieName.indexOf(";", begin);
if (end == -1) end = cookieName.length;
return unescape(cookieName.substring(begin + prefix.length, end));
}
var value = getCookie('nameCookie');
document.getElementById(value).style.height = "10%";
following code also doesn’t work
var value = getCookie('nameCookie');
if (value == 'test') {
document.getElementById('test').style.height = "10%";
}
Answer by Starx
Since you seem to be able to retrieve the value of the cookie
the problem is that when the code is running, it cannot find the element because the DOM is not ready yet. Make sure the script is running, after the element is loaded.
Just place your script block just before closing the </body>
.