4ever Youngz
4ever Youngz

Reputation: 158

Showing Content Based on Javascript Cookies

I am trying to create a newsletter section based off JS cookie. I have everything working correctly but displaying the content whether the cookie is there or not. I am using JS-cookie script.

I would like this section to only show up if the user does not have the cookie set already. Basically, if it's their first time viewing the site or after the cookie expires (30 days).

Right now, even if I use private browser, different computer, etc, it keeps saying the cookie is set and displaying the content. My current code has it when it's not set, so you won't see the div display unless you remove the ! from if statement.

I am using js-cookie for the cookies. You can see codepen http://codepen.io/byoungz/pen/YqoxJy

var emailSignup = document.getElementById("tgs-subscribe-bar"),
    screenWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);

$('#tgs-subscribe-bar').hide();


if (Cookies.get('emailsignup') == 'null') {
    if (screenWidth < 768) {
    //code for smaller screens      
    setTimeout(function() {
            $('#tgs-subscribe-bar').slideDown();
    }, 4000);

    } else {
        //code for larger
        setTimeout(function() {
                $('#tgs-subscribe-bar').slideDown();
        }, 1000);
    }

    Cookies.set('emailsignup', 'seenemail', { expires: 30, path: '/' });
}

 $('.email-exit').click(function() {     
      $("#tgs-subscribe-bar").slideToggle();
});

Upvotes: 1

Views: 510

Answers (1)

Cornwell
Cornwell

Reputation: 3410

If the cookie does not exist, it will return undefined not the string null

Try this:

    var emailSignup = document.getElementById("tgs-subscribe-bar"),
    screenWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);

$('#tgs-subscribe-bar').hide();


if (!Cookies.get('emailsignup')) {
    if (screenWidth < 768) {
    //code for smaller screens      
    setTimeout(function() {
            $('#tgs-subscribe-bar').slideDown();
    }, 4000);

    } else {
        //code for larger
        setTimeout(function() {
                $('#tgs-subscribe-bar').slideDown();
        }, 1000);
    }

    Cookies.set('emailsignup', 'seenemail', { expires: 30, path: '/' });
}

 $('.email-exit').click(function() {     
      $("#tgs-subscribe-bar").slideToggle();
});

Upvotes: 1

Related Questions