Javascript Cookie function only working on index file

219 views Asked by At

I've created a function to show a cookie policy in my website. The cookie is stored across the website and is working fine but the show/hide part of it only works in the index file and not in all the other pages and I can't understand why.

The function is as follows:

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 var 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;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

 (function() {
    var InfoCookieCont = jQuery('#info_cookie');
    var InfoCookieDiv = jQuery(".ok-cookie");
    InfoCookieDiv.click(function() {
     createCookie('infoCookie','true',365)
     InfoCookieCont.removeClass("cookie-visible").addClass("cookie-hidden");
    });

    var InfoCookie = readCookie("infoCookie");
    if (!InfoCookie) {
     InfoCookieCont.removeClass("cookie-hidden").addClass("cookie-visible");
    }
   })();

This installs a cookie from my website and until you click the .ok-cookie button, the #info_cookie will keep showing up on top of the page thanks to the .cookie-visible class.

This works fine on index.php, but not in the other pages. In other pages it keeps the .cookie-hidden class even if I didn't click the ok-cookie button in the previous page.

The .js file where this function is, is of course included in every page of my website.

The live website is: www.valeriopierbattista.com

thanks for your help, im going crazy!

1

There are 1 answers

2
jx12345 On BEST ANSWER

You've got some other js errors on the other pages which are killing the js script.

enter image description here