jquery cookie increment each visit?
-
14-07-2021 - |
문제
I am using jquery cookies plugin, in order to increment the value of the cookie each time a user comes to a page. I am doing this so I can display something on the first visit, then something different on the second visit and then nothing after that.
So i need to determine if its the user's first visit, their second visit and all visits after.
var cookieTime = jQuery.cookie('shownDialog');
cookie_value = parseInt(cookieTime);
if (cookieTime != 'true') {
jQuery.cookie('shownDialog', '1', 'true', {expires: 7});
cookie_value ++;
}
else if (cookieTime == 'true' && cookie_value > 0){
cookie_value ++;
}
This code i've been using gets reset every time i refresh the page. Instead of holding the value inside the cookie. I am not sure the best way of retaining the value of the cookie and incrementing it each time as the page gets refreshed?
해결책
I don't think
jQuery.cookie('shownDialog', '1', 'true', {expires: 7});
is the valid form. It's supposed to be
jQuery.cookie(cookiename, cookieval, extra);
Source: https://github.com/carhartl/jquery-cookie
If you want to check if the cookie is set, check if it's null.
// Check if the cookie exists.
if (jQuery.cookie('shownDialog') == null) {
// If the cookie doesn't exist, save the cookie with the value of 1
jQuery.cookie('shownDialog', '1', {expires: 7});
} else {
// If the cookie exists, take the value
var cookie_value = jQuery.cookie('shownDialog');
// Convert the value to an int to make sure
cookie_value = parseInt(cookie_value);
// Add 1 to the cookie_value
cookie_value++;
// Or make a pretty one liner
// cookie_value = parseInt(jQuery.cookie('shownDialog')) + 1;
// Save the incremented value to the cookie
jQuery.cookie('shownDialog', cookie_value, {expires: 7});
}