Reputation: 45
This isn't a Google Analytics type of thing (although I wish it were).
What I need to do is -- as dumb as it sounds -- count user clicks throughout their visit to a site (a WordPress site FYI). When they reach five clicks, then a popup modal will show. It has to be 5 clicks either on one page OR throughout the entire site (i.e. count their clicks as they visit multiple pages until the count is 5)
I figured I'd need to use cookies in order to keep track of the click count, although, I'm not sure what to do in order to keep the cookie consistently updated on click regardless of whether the user leaves a page to go to another or stays on one page.
I was thinking about PHP session variables since this is a WordPress site but I don't know if that's necessary? I'm just counting clicks, not storing any specific user data.
This is what I have going so far. Currently, the while just counts to 5 after a single click, which is not ideal.
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1);
}
if (c.indexOf(name) === 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
let click = getCookie("click");
if (click === 5) {
alert("stop counting: " + click);
} else {
$(document).on("click", function () {
let count = 1;
while (click < 5) {
click = count++;
setCookie("click", click, 30);
console.log("click count is: " +click);I
}
if (click === 5) {
alert("5 clicks reached!");
}
});
}
}
checkCookie();
Upvotes: 1
Views: 2309
Reputation: 138307
localStorage
let's you store data across tabs, and it is way more flexible than cookies. To count clicks you could listen to all clicks on the window
object:
window.addEventListener("click", () => {
let count = +localStorage.getItem("clickCount") || 0;
count += 1;
localStorage.setItem("clickCount", count);
if(count >= 5) {
//...
}
});
Upvotes: 1