Saving menu state on page reload - javascript

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!

Related

localStorage SET for just one day

I need to put up a pop up. It will be updated daily, so the pop up needs to show every day on page load if a user comes to the website, (new users and even users that have visited before) but if the user clicks the notice away, it needs to stay hidden for 24 hours, before resetting. I've written this code but can't get it to compare itself with the last time it was shown, using localStorage.
var modal = document.querySelector(".opening-modal");
var close = document.getElementById("pageDiv");
var element = document.getElementById("pageDiv");
function popupShown() {
if (!localStorage.getItem('showPopup')) { //check if popup has already been shown, if not then proceed
localStorage.setItem('showPopup', 'true'); // Set the flag in localStorage
element.classList.add("show-modal");
}
}
function closeModal() {
element.classList.add("hide-modal");
}
window.setTimeout(popupShown, 1500);
window.addEventListener("click", closeModal);
I'd give each modal an ID (ascending) and store the ID of the last modal the user dismissed. That way, if the modal doesn't change for 48 hours instead of 24, the user isn't shown the modal again.
var popupId = 42; // This is the number that changes when the content changes
if (+localStorage.dismissedPopup !== popupId) {
// Either the user has never dismissed one of these, or it's not the most recent one
window.setTimeout(popupShown, 1500);
}
function closeModal() {
element.classList.add("hide-modal");
// Remember the ID of the most recent modal the user dismissed
localStorage.dismissedPopup = popupId;
}
If you want to drive this from the HTML, the ID can come from a data-* attribute:
<div id="pageDiv" data-popup-id="42">An important update about...</div>
Then:
var popupId = +element.getAttribute("data-popup-id");
But if you want it to be time-based, store the time it was last dismissed:
if (!localStorage.lastPopupDismissed ||
(Date.now() - localStorage.lastPopupDismissed) > (24 * 60 * 60 * 1000))) {
window.setTimeout(popupShown, 1500);
}
function closeModal() {
element.classList.add("hide-modal");
// Remember the ID of the most recent modal the user dismissed
localStorage.lastPopupDismissed = Date.now();
}

How do i pop message and set expire time to that message state stored in local storage?

if(localStorage.getItem('popState') != 'shown'){
$(function () {
$('[data-toggle="popover"]').popover({
content : "....."
});
$('[data-toggle="popover"]').popover('show');
});
localStorage.setItem('popState','shown')
}
I am using the method above to display popup message to user during page load, and disable the popup message to be displayed after load for second time. How can i make it auto pop out to the user after certain period of time? e.g. after user close the popup message then it will be displayed automatically after an hour.
You can use an interval for this:
const showPopup = function showPopup() {
const lastShown = localStorage.getItem('popStateLastShown');
const hasOneHourPassed = lastShown ?
(Math.abs(new Date(lastShown) - new Date()) / 36e5) >= 1 :
false;
if (hasOneHourPassed || localStorage.getItem('popState') !== 'shown') {
// Show popup
localStorage.setItem('popState', 'shown');
localStorage.setItem('popStateLastShown', new Date());
}
};
// Run code immediately.
showPopup();
// Check again after an hour.
setInterval(showPopup, 36e5);

prevent pop up after refresh the page

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

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.

continue looping after alert message

Below is the function use to check for the session of my page. The page will reload after I clicked the alert message.
var timeleft = 60;
function checkTime() {
timeLeft--;
if (timeLeft == 30 )
{
alert("30 secs left.");
window.location.reload();
}
}
Is there anyway that the timeleft continue minus (if the user din't not notice the alert message) so that it will redirect to logout page when the timeleft is = 0.
alert() is a modal, it stops javascript execution. Check this code:
var start = new Date();
var start2;
window.setTimeout(function() {
var end = new Date();
var result = "time from start: " + (end.getTime() - start.getTime())
result += "\ntime from alert: " + (end.getTime() - start2.getTime())
result += "\nalert was open for: " + (start2.getTime() - start.getTime())
alert(result);
}, 500);
window.setTimeout(function() {
alert("hello");
start2 = new Date();
}, 100);
Fiddle for upper code: http://jsfiddle.net/aorcsik/vfeH2/1/
Check out this code, it shows that even setTimeout is stopped during alert(), but you can check how much time the user was looking at the alert, and update your counter (timeLeft) by decreasing with the measured time devided by your ticker delay.
Solution: So my solution would be to measure how much time the user looks at the alert modal, and whenever he clicks ok, check if his session ended, if yes redirect to logout, else do the usual redirect.
var start = new Date();
alert("xxx");
var t = (new Date()).getDate() - start.getDate();
if (t / 1000 > timeLeft) {
/* logout */
} else {
/* redirect */
}
Note: another solution would be to use some html popup instead of the javascript alert, which would not block javascript execution
If you want an async alert you can try this
setTimeout(function() { alert('30 secs left'); }, 1);
But if you want a timed logout you can do something like this instead:
function checkTime() {
setInterval(function(){alert("30 secs left.")},30000); // shown at 30 seconds
setInterval(function(){logout()},60000); // called at 60 seconds
}
function logout() {
// logout functionality
}
your code comment is strange
first you are using a number (60) and you consider it as (two minutes) then alert it is(30 seconds left)..
Anyways ..
you want to count down and when there is only 30 seconds left you want to reload the page!!
the problem here is that when you reload the page you will reset the count down from (60 as in your code)
the solution is one of the following:
1- save the countdown in localstorage as pointed out by #Fabrizio and when the page is reloaded again then use the saved counterdown value.
however this solution assume that your user browser can save to localstorage
2- second solution is that you post your page with the countdown and reload it with the count down..
let us say that you page address is: www.myexampleaddress.com/mypage
then you call the address as follow :www.myexampleaddress.com/mypage?timeleft=30
and catch this on the server and reload the page from the server with value in your querystring ..
so your coude after the alert should be like this
var myURL = location.href+'?timeleft=30';
location.href =myURL;
i hope that help :)

Categories

Resources