user3304303
user3304303

Reputation: 1043

How to correctly GET javascript Cookie?

On this test site, I had a fancybox lightbox popping up fine. Then I added code in hopes to have it only popup on FIRST visit, but never again after. So I have some JS below that runs setCookie() when either link in the lightbox is clicked. And onload, I run checkCookie(). If the cookie exists, don't show the lightbox. If it doesn't exist, show the lightbox.

With my new setting, getting and checking code, I can't get the lightbox to work now, and I'm pretty sure it's because getCookie isn't properly "getting" the cookie. Does anyone see anything obviously wrong?

function setCookie() {
document.cookie="lightboxcookie=lightboxseen; expires=Thu, 18 Dec 2020 12:00:00 UTC";
}

function getCookie(cname) {
    var name = cname + "=";
    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);
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function checkCookie() {
 var thecookie=getCookie("lightboxcookie");
    if (thecookie != "") {
        } else {
            <!--Show Lightbox-->
            jQuery.noConflict()(function ($) { 
                $(document).ready(function() { 
                    $(".lightbox").fancybox();
                    $(".lightbox").eq(0).trigger('click');
                    $(".lightbox").fancybox({
                        helpers : {
                            overlay : { 
                                css : {
                                    opacity: 0.8,
                                    'background-color' : '#ff0000'
                                }
                            }
                        }
                    });
                });
            });
       }
    }
}

</script>

Upvotes: 1

Views: 61

Answers (1)

Thomas C. G. de Vilhena
Thomas C. G. de Vilhena

Reputation: 14545

It seems that you have one extra closing curly brace at the end of your checkCookie function. If you remove that your code appears to be working as expected: http://jsfiddle.net/akk6wx9q/

By the way, if you are going to handle cookies in the client side using JavaScript I suggest you take a look at the well tested and easy to use Cookie.js library. By using it you can save a lot of time and the pain of trying to develop cookie handling functions yourself ;)

Upvotes: 1

Related Questions