Run same js code on every page in website - javascript

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>

Related

How to only show pop up on first page load

I am trying to only display a pop up on the first page load, but in my current script it only shows the pop up if you refresh the page. The popup should display the first time you come to the page but not again.
<script type="text/javascript">// <![CDATA[
document.addEventListener('DOMContentLoaded', function() {
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 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 '';
}
$(document).ready(function() {
if(getCookie('popup') !== ''){
$('.popup-wrapper').css('display','block');
} else {
setCookie('popup','open',1);
}
$('.popup-close').click(function(){
setCookie('popup','close',1);
$('.popup-wrapper').css('display','none');
});
});
});
// ]]></script>
Any help would be greatly appreciated.
Is there a reason why you are using cookies?? If not you can use localStorage and write something a bit cleaner..
So for example
$(document).ready(function() {
// if localStorage doesnt have the shownPopUp item
if(!localStorage.getItem('shownPopUp')){
$('.popup-wrapper').css('display','block');
}
$('.popup-close').click(function(){
// set the shownPopUp item in localStorage
localStorage.setItem('shownPopUp', true)
$('.popup-wrapper').css('display','none');
});
});
});
No need for the getCookie function
Cookies are more used for server-side functions, where localStorage is better for client-side functions. So what will happen here is your users will never see the popup again unless they delete there localStorage
Just add localStorage.setTtem after showing the popup. And don't forget to make the .popup-wrapper display:none
if(!localStorage.getItem('shownPopUp')){
$('.popup-wrapper').css('display','block');
localStorage.setItem('shownPopUp', true);
}

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.

Hide delayed div to new visitor, show immediately to returning visitor

I've found similar code elsewhere on this site but can't get it to work for my situation.
I'm trying to delay showing a div (8 second delay in this case) to NEW visitors but if cookie is set then show the div immediately to RETURNING visitors.
Currently, it seems that the first part works--showing the div to new visitors after 8 seconds--and my code sets the cookie but the second part--showing the div immediately to returning visitors--doesn't work at all and, in fact, NEVER seems to show the div content.
I've tried everything I can think to move around but no luck.
Here's the relevant code (including cookie code) all placed in the HEAD section:
<script type="text/javascript">
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;
}
</script>
<script type="text/javascript">
function showbox() {
document.getElementById("show-this").style.visibility = "visible";
}
if (!readCookie('visitedPreviously')) { //if he/she is a new user
setTimeout("showbox()", 8000); // after 8 secs createCookie('visitedPreviously', 'visitedPreviously', 3); // 365 days persistence
}
</script>
<div id="show-this" style="visibility: hidden"><div class="center-this"><img src="mysource" alt="some text" /></div>
</div>
I've tried moving the "function showbox" to the BODY, tried if/else statements inside that function, moving code to a .js files, using css, and more but now I just need some help as I obviously don't know what I'm doing.
Thank you for your time.
if (!readCookie('visitedPreviously')) { //if he/she is a new user
setTimeout("showbox()", 8000); // after 8 secs
createCookie('visitedPreviously', 'visitedPreviously', 3); // 365 days persistence
} else {
showbox();
}
you just forgot the else :)

Categories