I am trying to find how may I set a javascript cookie so it displays a fancybox popup after say 4-th pageview of visitor.
Here is the code that I am using to display
As mentioned in the comments by @Gregdebrick the answer is being update to use the JavaScript Cookie plugin https://github.com/js-cookie/js-cookie instead of the deprecated jQuery Cookie plugin.
So, after loading the JS Cookie plugin from CDN in your page:
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
Use the following script:
$(document).ready(function () {
// if the cookie is undefined, create it
if(typeof Cookies.get('visited') === "undefined"){
Cookies.set("visited", 0);
}
// Cookies.get('visited') returns a string
if (parseInt(Cookies.get('visited')) >= 3) {
// open fancybox after 3 secs on 4th visit
setTimeout(function () {
$.fancybox.open({
// your fancybox API options here
});
}, 3000);
} else {
let increase = parseInt(Cookies.get('visited')) + 1;
Cookies.set('visited', increase, { expires: 1 });
return false;
}
}); // ready
See updated working DEMO
Assuming that you are using the jQuery Cookie Plugin, then you could use the following code to launch fancybox after 3 seconds, the 4th page visit on the same day :
$(document).ready(function () {
// create cookie
var visited = $.cookie('visited'); // visited = 0
if (visited >= 3) {
// open fancybox after 3 secs on 4th visit or further on the same day
setTimeout(function () {
$.fancybox.open({
// your fancybox API options here
});
}, 3000);
} else {
visited++; // increase counter of visits
// set new cookie value to match visits
$.cookie('visited', visited, {
expires: 1 // expires after one day
});
return false;
}
}); // ready
See working DEMO