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>.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!