简体   繁体   中英

add cookie if no cookie of that name exists jquery

I have a splash page where the user chooses between 2 experiences. once chosen, a cookie is added so they will always get that experience (or at least for the next 30 days). however, if a user comes to the site directly to a sub-url and bypasses the splash page, they should be automatically added to the default experience and get the default cooke (theme1). everything except the default cookie part is working.

here's what i have:

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;
}
$('.theme2').click(function() {     
    createCookie('chooseTheme','chosenTheme2',30)       
});
$('.theme1').click(function() {     
    createCookie('chooseTheme','chosenTheme1',30)       
}); 
var x = readCookie('chooseTheme');
if ($.cookie('chooseTheme') === null) {
    createCookie('chooseTheme','chosenTheme1',30);      
} 
if (x.indexOf('chosenTheme1') > -1) {
    $('body').addClass('themeOne');
} else if (x.indexOf('chosenTheme2') > -1) {
    $('body').addClass('themeTwo');
} 

thanks!

Try running a loop that updates every 1 minute. During the update, it triggers the function that checks for the cookie like the following:

setInterval(checkCookie(), 60000);
//the 60000 is for 60000 milliseconds which is 1 minute.
function checkCookie() {
    var x = readCookie('chooseTheme');
    if ($.cookie('chooseTheme') === null) {
    createCookie('chooseTheme','chosenTheme1',30);      
    } 
    if (x.indexOf('chosenTheme1') > -1) {
        $('body').addClass('themeOne');
    } else if (x.indexOf('chosenTheme2') > -1) {
    $('body').addClass('themeTwo');
    }
}

Then add the code above into your code and it will check for the theme every 1 minute. I hope this helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM