Toggling cookie contents?

I’m trying to make a button to toggle the presence of a cookie (as well as another element on the page).

I have the script below, however it doesn’t seem to work.

How I find the cookie in javascript and parse it’s contents to see if the value is set or not?

window.addEventListener('load', function() {

    let bt = document.getElementById('agentbar-button');
        bt.addEventListener('click', function(){

            //close the cookie notice

            //set the cookie

            if (document.cookie.indexOf("cookie-accepted=") != 1){
                document.cookie = 'cookie-accepted=1; expires=Thu, 1 Jan 2100 12:00:00 UTC; path=/';
                alert("not here");
            } else {
                document.cookie = 'cookie-accepted=; expires=Thu, 1 Jan 2100 12:00:00 UTC; path=/';



This line seems off:

if (document.cookie.indexOf("cookie-accepted=") != 1){

There is no reason for that text to appear at position 1, given that the first index of a string is 0.
Furthermore, there is no need to assume that it will always be the first cookie in the document.

So I’d change that to

if (document.cookie.indexOf("cookie-accepted=") !== false) {

which basically means “if the string does not not appear in the cookie”, which is the same as “if the string does appear in the cookie”.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.