prevent pop up after refresh the page - javascript

I'm creating a popup that will show when the user scrolls. However when the user clicks on the close button and refreshes the page and scrolls, I need to make a popup to show up after 10 minutes.
var popUp= document.getElementById("popup");
var closePopUp= document.getElementsByClassName('popup-close');
var halfScreen= document.body.offsetHeight/2;
var showOnce = true;
//show when scroll
window.onscroll = function(ev) {
if ((window.innerHeight+window.scrollY) >= halfScreen && showOnce) {
if(popUp.className === "hide"){
popUp.className = "";
}
showOnce = false;
}
};
//close button
for(var i = 0; i<closePopUp.length; i++){
closePopUp[i].addEventListener('click', function(event) {
if(popUp.className === ""){
popUp.className = "hide";
}
});
}

First you should detect whether the user has refreshed the page.You can achieve this using navigator object.Refer this question for implementation.
Secondly, once the user refreshes the page all the variables gets destroyed and initialized again.Hence you must use cookies or server side sessions to store whether user has already closed it once.But I always recommend you to setup sessions since cookies can be disabled by users.
To sum it up,setup an ajax request once the user refreshes the page,and if already he has closed the popup once, start a timeout for 10 minutes.
Adding a sample prototype for this :
var refreshed = false;
if (performance.navigation.type == 1) {
console.info( "This page is reloaded" );
refreshed = true;
} else {
console.info( "This page is not reloaded");
refreshed = false;
}
if(refreshed) {
//implement this ajax function yourself.
ajax('path/to/yourserver','method','data',function(response) {
if(response == "showed") {
var time = 10 * 60 * 1000;//10 minutes.
setTimeout(function() {
//show your popup.
},time);
}else {
//immediately show once scrolled.
}
});
}

You should use cookie for this and set cookie expiration time for 10 minutes take a look at this cookie plugin hope it helps
Set a cookie
$.cookie("example", "foo"); // Sample 1
$.cookie("example", "foo", { expires: 7 }); // Sample 2
Get a cookie
alert( $.cookie("example") );
Delete the cookie
$.removeCookie("example");
Or there is an example which is given in this answer take a look at this also

Related

Save in localstorage and db and show it later

I use Elementor Pro.
I have a button that is limited to 7 clicks, when clicking number 7 is disabled, and this is saved in localstorage to display later.
My problem if the user login from different device, the count start againg in 0. and obviously the code don't work for my need, The user after 7 click Never can click again.
How can resolve this?
this is the code:
<script>
// On page load (or in whatever event creates the button)
window.addEventListener("load", ()=>{
// Read the saved state from local storage (if not yet saved, will be null)
let clickcount3 = localStorage.getItem("localStorage.clickcount3");
if(localStorage.clickcount3>6)
document.getElementById("showResultMasPack").style.visibility = "visible";
});
function CounterMastPack() {
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount3) {
localStorage.clickcount3 = Number(localStorage.clickcount3)+1;
} else {
localStorage.clickcount3 = 1;
}
document.getElementById("resultMastPack").innerHTML = localStorage.clickcount3 + " Click(s).";
} else {
document.getElementById("resultMastPack").innerHTML = "Sorry, your browser does not support web storage...";
}
if(localStorage.clickcount3>6)
document.getElementById("showResultMasPack").style.visibility = "visible";
}
</script>

Measure time spent by a user during a website visit

I'm trying to build a website locally using PHP and Javascript and MAMP.
What I'm looking for is to put a timer on every page of the website and that timer counts the time spent by the user in the whole website. Even if the user switches between pages the timer will still continue. The solution I've found only shows the time spent on each page and when I reload the same page again the timer restart from zero.
Here's the Javascript for the timer I did:
window.onload=function(){
time=0;
}
window.onbeforeunload=function(){
timeSite = new Date()-time;
window.localStorage['timeSite']=timeSite;
}
I've search everywhere for the solution but with no luck, if anyone knows how to do this please let me know.
Here's a working example. It will stop counting when the user closes the window/tab.
var timer;
var timerStart;
var timeSpentOnSite = getTimeSpentOnSite();
function getTimeSpentOnSite(){
timeSpentOnSite = parseInt(localStorage.getItem('timeSpentOnSite'));
timeSpentOnSite = isNaN(timeSpentOnSite) ? 0 : timeSpentOnSite;
return timeSpentOnSite;
}
function startCounting(){
timerStart = Date.now();
timer = setInterval(function(){
timeSpentOnSite = getTimeSpentOnSite()+(Date.now()-timerStart);
localStorage.setItem('timeSpentOnSite',timeSpentOnSite);
timerStart = parseInt(Date.now());
// Convert to seconds
console.log(parseInt(timeSpentOnSite/1000));
},1000);
}
startCounting();
Add the code below if you want to stop the timer when the window/tab is inactive:
var stopCountingWhenWindowIsInactive = true;
if( stopCountingWhenWindowIsInactive ){
if( typeof document.hidden !== "undefined" ){
var hidden = "hidden",
visibilityChange = "visibilitychange",
visibilityState = "visibilityState";
}else if ( typeof document.msHidden !== "undefined" ){
var hidden = "msHidden",
visibilityChange = "msvisibilitychange",
visibilityState = "msVisibilityState";
}
var documentIsHidden = document[hidden];
document.addEventListener(visibilityChange, function() {
if(documentIsHidden != document[hidden]) {
if( document[hidden] ){
// Window is inactive
clearInterval(timer);
}else{
// Window is active
startCounting();
}
documentIsHidden = document[hidden];
}
});
}
JSFiddle
Using localStorage may not be the best choice for what you need. But sessionStorage, and localStorage is most suitable. Have in mind that sessionStorage when opening a new tab resolves to a new session, so using localStorage has to do with the fact that if only sessionStorage was used and a user opened a new tab in parallel and visit your website would resolve to a new separate session for that browser tab and would count timeOnSite from start for it. In the following example it is tried for this to be avoid and count the exact timeOnSite.
The sessionStorage property allows you to access a session Storage
object for the current origin. sessionStorage is similar to
Window.localStorage, the only difference is while data stored in
localStorage has no expiration set, data stored in sessionStorage gets
cleared when the page session ends. A page session lasts for as long
as the browser is open and survives over page reloads and restores.
Opening a page in a new tab or window will cause a new session to be
initiated, which differs from how session cookies work.
function myTimer() {
if(!sessionStorage.getItem('firstVisitTime')) {
var myDate = Date.now();
if(!localStorage.getItem('timeOnSite')) {
sessionStorage.setItem('firstVisitTime',myDate);
} else {
if(localStorage.getItem('tabsCount') && parseInt(localStorage.getItem('tabsCount'))>1){
sessionStorage.setItem('firstVisitTime',myDate-parseInt(localStorage.getItem('timeOnSite')));
} else {
sessionStorage.setItem('firstVisitTime',myDate);
}
}
}
var myInterval = setInterval(function(){
var time = Date.now()-parseInt(sessionStorage.getItem('firstVisitTime'));
localStorage.setItem('timeOnSite',time);
document.getElementById("output").innerHTML = (time/1000)+' seconds have passed since first visit';
}, 1000);
return myInterval;
}
window.onbeforeunload=function() {
console.log('Document onbeforeunload state.');
clearInterval(timer);
};
window.onunload=function() {
var time = Date.now();
localStorage.setItem('timeLeftSite',time);
localStorage.setItem("tabsCount",parseInt(localStorage.getItem("tabsCount"))-1);
console.log('Document onunload state.');
};
if (document.readyState == "complete") {
if(localStorage.getItem("tabsCount")){
localStorage.setItem("tabsCount",parseInt(localStorage.getItem("tabsCount"))+1);
var timer = myTimer();
} else {
localStorage.setItem("tabsCount",1);
}
console.log("Document complete state.");
}
Working fiddle
If you want a server-side solution then set a $_SESSION['timeOnSite'] variable and update accordingly on each page navigation.

localStorage get empty when i refresh the page

localStorage gets empty when i refresh the page.
What i have done in code is :-
1)I have store the authToken in localStorage
2)I have store isReloaded value in sessionStorage to check if page is new open or is postback
If browser tab is first time open then increment the browser tab count value in tabCount localStorage and if browser is reloaded then no value should be added in tabCount and if i close all the tabs without logout of page all localStorage should get clear.
Purpose of code to achieve : -
1) page should clear the localStorage values if all the browser tabs are closed without logout of the page.
2) instance of page should open in multiple tabs
$(window).load(function () {
if(!sessionStorage.getItem('isReloaded'))
{
//first time call
if(localStorage.getItem('tabCount') == null || localStorage.getItem('tabCount') == undefined)
{
var tabCount = 1;
localStorage.setItem('tabCount',tabCount.toString());
}
else
{
var tabCount = parseInt(localStorage.getItem('tabCount'));
tabCount += 1;
localStorage.setItem('tabCount',tabCount.toString());
}
}
else
{
// postback code here
console.log('in postback...')
}
sessionStorage.setItem('isReloaded',true);
});
$(window).unload(function(){
var tabCount = parseInt(localStorage.getItem('tabCount'));
if(tabCount > 0)
{
tabCount -= 1;
if(tabCount == 0)
{
//RemoveLocalStorage('tabCount,authToken,userId,userName,userFullName,caseNo,consumerName, consumerFirstName, consumerLastName, consumerList, userData,timeStamp');
localStorage.setItem('tabCount',tabCount.toString());
localStorage.clear();
}
else
{
localStorage.setItem('tabCount',tabCount.toString());
}
}
});

Leaving a page - message appears twice

I've added this Javascript to my website which detects when the user navigates away from the page, but I only want a warning to appear if the navigator is offline AND one of my elements contains the word "unsaved":
window.thisPage = window.thisPage || {};
window.thisPage.closeEditorWarning = function (event) {
if (navigator.onLine===false) {
// See if any fields need saving...
for (i = 1; i <= 500; i++) {
try {
ToSave = document.getElementById("Q" + i).innerHTML;
if (ToSave.indexOf("unsaved")!=-1) {
return "You are currently offline and some of your responses are not yet saved.\r\n\r\nIf you want to save the changes you've made, choose to 'Stay on this Page' and then reconnect to the internet and any unsaved responses will save automatically.";
}
}
catch(err) { }
// If got this far, nothing needs saving anyway...
}
}
return undefined;
};
window.onbeforeunload = window.thisPage.closeEditorWarning;
The code works fine except; if the message pops up the first time and I choose "Stay on this page", then try to navigate away again and the second time click "Leave this page" - rather than navigating away it displays the message again but I can't work out why.
Try returning true from your catch, so the unload will execute. You can also remove the return undefined; from the end.
This works for me, is this what you're after?
This works for me in Firefox.
Fiddle: http://jsfiddle.net/518myq0j/3/ (clicking 'Run' triggers the onbeforeunload)
Updated JavaScript code:
window.thisPage = window.thisPage || {};
window.thisPage.closeEditorWarning = function (event) {
if (navigator.onLine === false) {
// See if any fields need saving...
for (i = 1; i <= 5; i++) {
try {
var ToSave = document.getElementById("Q" + i).innerHTML;
if (ToSave.indexOf("unsaved") != -1) {
return "You are currently offline and some of your responses are not yet saved.\r\n\r\nIf you want to save the changes you've made, choose to 'Stay on this Page' and then reconnect to the internet and any unsaved responses will save automatically.";
}
} catch (err) {
return true;
}
}
}
};
window.onbeforeunload = window.thisPage.closeEditorWarning;

Saving menu state on page reload

I have a menu where I want the state open/close state to persist if the page reloads and when the user has clicked to be closed or open.
I'm using a cookie plugin and I'm almost there but I'm having trouble setting the close cookie to remember the close state, the open cookie still persists.
$(document).ready(function() {
// Open / Close Panel According to Cookie //
if ($.cookie('filtermenu') === 'open'){
$('.filter').show(); // Show on Page Load / Refresh without Animation
}
else {
}
if ($.cookie('filtermenu') === 'close' || $.cookie('filtermenu') === null){
$('.filter').hide(); // Show on Page Load / Refresh without Animation
}
else {
}
// Toggle Panel and Set Cookie //
$('#filter-menu').click(function(){
$('.filter').slideToggle('fast', function(){
if ($('#filter-menu').is(':hidden')) {
$.cookie('filtermenu', 'close', { expires: 30 });
} else {
$.cookie('filtermenu', 'open');
}
});
return false;
});
});
Can anyone please see what I'm doing wrong.
Thanks.
Update: Sorry, so now I have this, but it's still not staying closed, am I using the date object incorrectly?
Ok, so now I have this, but the menu still doesn't stay closed.
$(document).ready(function() {
// Open / Close Panel According to Cookie //
if ($.cookie('filtermenu') === 'open'){
$('.filter').show(); // Show on Page Load / Refresh without Animation
}
else {
}
if ($.cookie('filtermenu') === 'close' || $.cookie('filtermenu') === null){
$('.filter').hide(); // Show on Page Load / Refresh without Animation
}
else {
}
// Toggle Panel and Set Cookie //
$('#filter-menu').click(function(){
$('.filter').slideToggle('fast', function(){
var now = new Date();
var time = now.getTime();
time -= 60 * 1000;
now.setTime(time);
$.cookie('filtermenu', 'open', {expires: now});
if ($('#filter-menu').is(':hidden')) {
$.cookie('filtermenu', 'close', { expires: 30 });
} else {
$.cookie('filtermenu', 'open');
}
});
return false;
});
});
You are going to want to re-set the open cookie with an expiration date older than current time right before you set the close cookie. That way the open cookie will immediately expire and your closed cookie is what remains.
Update - Getting the time
You've inquired about getting the current time in JS, here is some sample code:
var now = new Date();
var time = now.getTime();
time -= 60 * 1000;
now.setTime(time);
This creates a new Date object called now and extracts the time from it with getTime(). We then subtract one minute of time (time is in milliseconds, so 60 * 1000), and then set the date back to that time. You can now use this Date object to set the expiration time of your cookie!

Categories

Resources