One-time alert keeps executing - javascript

I'm trying to get a one-time alert when a user visits a website, then place a cookie so they're not annoyed with it every time they come back to the site. The cookie is saved and the alert executing, but it KEEPS executing and I'm tearing my hair out.
I've tried a number of things found on the web (StackExchange, how I love thee) but none seem to work. Here's the current state:
<script>
function setCookie(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=/";
}
</script>
<body>
<script type="text/javascript">
if(!setCookie('testcookie')) {
alert("hello world");
setCookie('testcookie','1',3);
}
</script>
</body>
Looking at the cookie records, it seems to be setting every time. If I change the expiration date in the script, it changes in the dev console every time. Not sure if that's indicative of the problem or not.
===== END SOLUTION ======
I was missing the getCookie call. I also realized that when trying to add it to the header scripts, the execution needed to be it's own function * facepalm *. I also added all the scripts to the header and instead call the function in the body tag.
<head>
<script>
function setCookie(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=/";
}
var getCookie = function (c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
};
function checkCookie() {
if(!getCookie('testcookie2')) {
alert("hello world");
setCookie('testcookie2','1',3);
}
}
</script>
</head>
<body onload="checkCookie()">
</body>
TA-DA!

I use a little javascript function sometimes to retrieve cookies
var getCookie = function (c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
};
you can use this in conjunction with your other logic
if(!getCookie('testcookie')) {
alert("hello world");
setCookie('testcookie','1',3);
}

Related

How to hide a DIV when reloading a page?

I have a loading overlay that shows some information and I have a button to refresh the page. But I want the loading overlay only to appear once, not every time the button is clicked. (F5 doesn't matter). I was thinking of something like this:
<button type="button" onclick="reload();">
function reload() {
if (window.location.reload()) {
document.getElementById('loading').style.display = 'none';
}
}
But it doesn't work... pls help
You can make use of client cookie, set a flag to client cookie if overlay already shown once, example code:
Vanilla JS Version
<script>
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
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);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
if (getCookie('OVERLAY_ALREADY_SHOWN')) {
document.getElementById('loading').style.display = 'none';
}
else {
// ... some conditions ...
setCookie('OVERLAY_ALREADY_SHOWN', true, 14); // persist two weeks
}
</script>
jQuery Cookie Version
<script src="/path/to/jquery.cookie.js"></script>
<script>
if ($.cookie('OVERLAY_ALREADY_SHOWN')) {
document.getElementById('loading').style.display = 'none';
}
else {
// ... some conditions ...
$.cookie('OVERLAY_ALREADY_SHOWN', true, { expires: 14 }); // persist two weeks
}
</script>

How to disable popup from showing up on given page for 2 days after I click .popup-close on first visit to that page?

How to disable popup from showing up on given page for 2 days after I click .popup-close on first visit to that page ?
This is my code https://jsfiddle.net/4q1aL8pL/2/
I've tried localstorage between lines 122-140 in my code. I am javascript beginner please help :)
Maby there has to be some timer applied which will count to 2 days hours worth ?
//<![CDATA[
var n = Number(localStorage.getItem('odometerValue')) || 0;
var m = localStorage.getItem('displayNone');
var myOdometer;
function startcounting () {
var div = document.getElementById("odometerDiv");
myOdometer = new Odometer(div, {value: n, digits: 6, tenths: true});
myOdometer.set(n);
update();
}
function update () {
n=n+0.01
myOdometer.set(n);
localStorage.setItem('odometerValue', n);
localStorage.setItem('displayNone', m);
setTimeout(update, 200);
}
//]]>
you can use the local storage to save the date of when the pop up loaded.
var d = new Date();
this will stamp the current date then all you have to do is check with the date of the visitor again and if you minus them and it equals 2 days pop up again.
Here is a function for using cookies.
/* Show popup if cookie doesn't exist. Will hide for 2 days if closed */
var PopUpCookie = getCookie("MyPopUpCookie");
if (PopUpCookie == '') {
$('#odometerDiv').show();
} else {
$('#odometerDiv').hide();
}
}
$('.popup-close').on('click', function () {
$('#odometerDiv').hide();
setCookie("MyPopUpCookie", "hide");
});
function setCookie(cname, cvalue) {
var d = new Date();
d.setTime(d.getTime() + (2*24*60*60*1000)); /* 2 days */
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
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);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}

Timer that keeps counting when navigating away from page

I have a timer that counts down once a specific page is visited. I need this timer to keep counting even if someone goes to a different page, and maintain the time counted to display it on the screen when they return to the original page where it was triggered.
The code I have in place is
<script>
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;
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
//check existing cookie
cook=getCookie("test9_cookie");
if(cook==""){
//cookie not found, so set seconds=60
var seconds = '<?php echo OFFERTIME ?>';
}else{
seconds = cook;
console.log(cook);
}
// init var
var timeout = 0;
// end init var
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
//store seconds to cookie
setCookie("test9_cookie",seconds,1); //here 1 is expiry days
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
timeout = 1;
sessionStorage.setItem('nothanks', 1);
document.getElementById('timed-over').style.display = "block";
$("#timed-over").delay(4800).fadeOut(300);
document.getElementById('timed-container').style.display = "none";
} else {
seconds--;
}
}
var countdownTimer = setInterval(secondPassed, 1000);
//localStorage.removeItem('timedpid') //to delete localstorage during testing
function checktaken(){
if(timeout===1) {
//do nothing as expired
}else if(localStorage.getItem('timedpid')) {
var storedpid = localStorage.getItem('timedpid')
var currentpid =<?php echo json_encode($time_limited_pid); ?>;
if (storedpid !== currentpid) {
var showOffer = document.querySelector("#timed-container");
showOffer.style.display = "block";
}
}else if(sessionStorage.getItem('nothanks')) {
// do nothing as offer not wanted
}else{
var showOffer = document.querySelector("#timed-container");
showOffer.style.display = "block";
}
}
setInterval('checktaken()',1);
</script>
Is there any way to make the original code keep counting when the page the script is on is navigated away from?
If not, a solution would be to move part of the script to the header and have it only load when on a specific page. Doing this would mean having to pass a var from the script in the header, to a script in a different file. I'm not too clued up on javascript and haven't had any luck sharing variables across multiple pages before.
Stuff the start time into the cookie (or local storage, anything permanent) and use the difference between that start time and the current time for your timer.

Run same js code on every page in website

I'm trying to create a popup that opens after 30 seconds even if the user changes to a different page on the site.
e.g. User enters example.com and stays on the main page for 15 seconds, then navigates to a different page still on the site example.com, stays there for 15 seconds. Now I want the popup to open.
My JavaScript code to create a cookie:
<html>
<head>
<script>
var timeElapsed;
var targetTime = 10000;
var myInter;
function openPopup() {
alert('popup');
timeElapsed = 0;
clearInterval(myInter);
setCookie('alreadyDone', true, 1);
}
function updateCookie() {
timeElapsed += 2000;
setCookie('emailPopup', timeElapsed, 1);
alert(timeElapsed);
}
function checkCookie() {
if (getCookie('alreadyDone') === "") {
if (getCookie('emailPopup') === "") {
timeElapsed = 0;
setCookie('emailPopup', timeElapsed, 1);
} else {
timeElapsed = parseInt(getCookie('emailPopup'));
setCookie('emailPopup', timeElapsed, 1);
}
setTimeout(openPopup, targetTime - timeElapsed);
myInter = setInterval(updateCookie, 2000);
}
}
function getCookie(cname) {
var name = cname + "=";
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);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
</script>
</head>
<body onload="checkCookie()">
<button>Page 1</button>
</body>
But I need this code run on every page on my site.
1) Create a js file called your-name.js
2) Cut this code and paste there. Save.
3) Call this file in every of your webpages like
<html>
<head>
<script type="text/javascript" src="/your-location/your-name.js"></script>
<head>
<body>
</body>
<html>

Change HTML Button Based On Cookie Existance

I want to edit an html button that will tell the user if they have read the page that the button is on. The button is at the bottom of the page, and starts off being red. After the user presses the button, a cookie is generated and the changeButton() function checks to see if the cookie has been created, and then changes the button to green. Even after the user closes and reopens the browser, the button should stay green until the cookie has been deleted.
My browser just shows the button as being green on page loadup, before I even hit the button. Any help would be greatly appreciated.
<head>
<script type="text/javascript">
function changeButton()
{
var name = 'user_read_the_page' + '=';
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);
}
if(c.indexOf(name) != -1)
{
var output = c.substring(name.length,c.length);
}
}
document.getElementById("test").innerText = output;
if(output == 1)
{
cookie_exists = 1;
}
else
{
cookie_exists = 0;
}
if(cookie_exists == 1)
{
document.getElementById("read_button").style.backgroundColor = "green";
document.getElementById("read_button").style.color = "white";
document.getElementById("read_button").style.fontWeight = "bold";
document.getElementById("read_button").innerText = "\u2714 You Have Read This Page";
}
else
{
document.getElementById("read_button").style.backgroundColor = "red";
document.getElementById("read_button").style.color = "white";
document.getElementById("read_button").style.fontWeight = "bold";
document.getElementById("read_button").innerText = "\u2718 Please Read This Page";
}
return "";
}
</script>
</head>
...
<button id="read_button" onclick="createCookie('user_read_the_page', 30)"></button>
<script language="javascript">
function createCookie(name, days)
{
var expire = new Date ();
expire.setTime (expire.getTime() + (24 * 60 * 60 * 1000) * days);
document.cookie = name + "=1; expires=" + expire.toGMTString();
changeButton();
}
</script>

Categories