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>
Related
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
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.
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;
I have a JS that plays a notification sound on the arrival of any new notifications. It works completely fine when a new notification comes, it should play the sound and it does play.
The notification I am talking about is only an integer which is returned from a query through an ajax call. I set this integer into my <asp:label.../> through the script.
The problem is : I have written the script on MasterPage. So every time I open a new page, or a refresh the same one the <asp:Label.../> gets cleared which I set from my script using .html(value) causing the script to run the sound again as every time the page refreshes or another page is loaded.
The problem may be is , that the value is not persistent ?
I want that the value should be set to the html of the label and also its value should be persistent on all the pages . What should I do for this persistence ?
My Script is :
myFunction();
function myFunction() {
$.get("AjaxServicesNoty.aspx", function (data) {
var recievedCount = parseInt(data);
alert(recievedCount);
var existingCount = $(".lblEventCount").text();
if (existingCount == "") {
existingCount = 0;
alert(existingCount);
} else {
existingCount = parseInt($(".lblEventCount").text());
alert(existingCount);
}
// if (existingCount == "" && recievedCount != 0) {
// $(".lblEventCount").html(recievedCount);
// $(".lblAcceptedCount").html(recievedCount);
// var sound = new Audio("Sound/notificationSound.wav");
// sound.play();
// }
if ((parseInt(recievedCount) > parseInt(existingCount)) && existingCount == 0) {
$(".lblEventCount").html(recievedCount);
$(".lblAcceptedCount").html(recievedCount);
var sound = new Audio("Sound/notificationSound.wav");
sound.play();
} else {
$(".lblEventCount").html(existingCount);
$(".lblAcceptedCount").html(existingCount);
}
});
}
setInterval(myFunction, 5000);
use DIV ID instead of selecting via class
$("#divID").html(existingCount);
OPTIONS PAGE
// gets button from page
var checkButton = document.getElementById('saveCheck');
// initiates check fucntion when clicked
checkButton.addEventListener('click', check);
// starts when youtube setting is saved
function check() {
console.log('Check starts');
//initiates if checkbox is checked
if (check.checked) {
console.log('its checked');
localStorage.youtube = 1;
} else {
console.log('it isnt checked');
localStorage.youtube = 0;
}
}
console.log(localStorage.youtube);
This parts works perfectly, but when I try accessing the data stored in the local storage through my background.js page of my extension, it doesn't returns null for the values
BACKGROUND.JS
var ytcheck = localStorage.getItem('youtube');
console.log(ytcheck);