I'm struggling to add cookie control to my popup so it only shows once.
var modal = document.querySelector(".modal");
var close = document.getElementById("myDiv");
var element = document.getElementById("myDiv");
function popupScroll() {
element.classList.add("show-modal");
}
function closeModal() {
element.classList.add("hide-modal");
}
window.addEventListener("scroll", popupScroll);
window.addEventListener("click", closeModal);
You could use localStorage or sessionStorage.
While localStorage accesses the current domain's local Storage object and adds a data item to it, sessionStorageaccesses the current domain's session Storage object and adds a data item to it.
var modal = document.querySelector(".modal");
var close = document.getElementById("myDiv");
var element = document.getElementById("myDiv");
function popupScroll() {
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.addEventListener("scroll", popupScroll);
window.addEventListener("click", closeModal);
Remember, while an item that has been set in sessionStorage lasts as long your browser session, the localStorage items don't have expiration times. That being said, in your current case, you could use either localStorage or sessionStorage.
I advice to use localStorage. Its a Javascript API with functions like setItem and getItem. Here an example:
function displayPopup() {
//if the variable in localStorage is set dont show the popup and just return
if (localStorage.getItem('popupAlreadyShown')) return;
//display popup, example:
document.getElementById('popup').style.display = 'block';
}
function closePopup() {
//close popup, example:
document.getElementById('popup').style.display = 'none';
//set the variable in localStorage that the popup is closed
localStorage.setItem('popupAlreadyShown', 'true');
}
Related
Good evening,
i was working on a part of what i hope will be my future website and i wanted to add a "photograpy" section to it, and here comes the problem.
since the title in the main page constatly changes color, i'd like to grab its current color to transfer it to the title of the other page to play an animation later on.
the problem is that when i press the related button, i am taken to the photograpy page, but the title remains black.
i've tried seraching for help on google but i haven't been able to find much.
here is the JS
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", function() {
loaded();
});
} else if (document.attachEvent) {
document.attachEvent("onreadystatechange", function() {
loaded();
});
}
function loaded() {
document.getElementById("PHtitle").style.color === titlecolor;
}
function script() {
const titlecolor = document.getElementById("title").style.color;
};
document.getElementById('photograpy').onclick = function () {
script();
};
The snippets don't allow for localStorage, so here is just the javascript.
First, I let the variables outside of a function. The titleColor function checks to see if titleColor was saved in localStorage, if not the default color is black.
Then I set the color of the phtitle to the contents of titleColor variable.
In the script function, I set the localStorage variable to the getComputedStyle color of the title.
Then last I use an event listener on the button to run the script for saving the color.
LocalStorage is a way to store data in the user's browser until they close their browser/clear their data etc.. Which will allow it to be usable on different pages then where it was saved.
let titleColor = localStorage.getItem("titleColor") || "#000000";
let PHtitle = document.querySelector("#PHtitle");
let title = document.querySelector("#title");
let btn = document.querySelector("#photography");
if(PHtitle){
PHtitle.style.color = titleColor;
}
function script() {
localStorage.setItem("titleColor", getComputedStyle(title).color)
}
if(btn && title){
btn.addEventListener("click", function() {
script();
})
}
Can someone help me save a toggled class in localstorage so that every time I reload the the page the toggled class will still be there.
$('[data-toggle=collapse]').click(function() {
$('#down-right').toggleClass('fa-chevron-down fa-chevron-right');
if (window.localStorage.toggled != "fa-chevron-down") {
$('#down-right').toggleClass("fa-chevron-down", true);
window.localStorage.toggled = "fa-chevron-down";
} else {
$('#down-right').toggleClass("fa-chevron-right", false);
window.localStorage.toggled = "fa-chevron-right";
}
});
Store state in localStorage
localStorage.setItem('state',state) // for storing
Read On Page reload
window.document.onload = function(e){
const state = localStorage.getItem("state"); // for retrieving
}
window.onload = function(e){
const state = localStorage.getItem("state"); // for retrieving
}
I have a user script that does some stuff after clicking a button. By clicking the same button again (like a toggle button), I want it to 'revert' back to default. By default I mean the on page load content. Check my code:
var myTbl = document.getElementsByClassName("myTable")[0];
var myCells = myTbl.getElementsByTagName("td");
myCells[2].innerHTML = "<span id='myButton' class='button'>Do something / Revert</span>";
document.getElementById("myButton").addEventListener("click", doSomething, false);
function doSomething() {
// do some stuff with myTbl
document.getElementById("myButton").removeEventListener("click", doSomething, false);
document.getElementById("myButton").addEventListener("click", revertToDefault, false);
}
function revertToDefault() {
// location.reaload();
}
I could do it with location.reaload();, but that's not what I want. I would prefer to save the default on load content in a variable like I did with the variable myTbl var myTbl = document.getElementsByClassName("myTable")[0]; and preserve that default content and then simply save that default content in the variable myTbl myTbl = defaultTbl; when executing the revertToDefault() function. What's the correct code to do that? Is there a better way of doing that, perhaps without the need of saving everything in a variable?
A possible working solution:
var myTbl = document.getElementsByClassName("myTable")[0];
var defaultTbl = myTbl.innerHTML; // this way defaultTbl remains intact while manipulating myTbl object
function revertToDefault() {
myTbl.innerHTML = defaultTbl;
}
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.
So I have a website that loads pages to a container div:
function goto(addr) {
$("#content").load(addr);
}
and a link that executes it
About us
My problem is that whenever the page is refreshed, the loaded content resets to the default page (page/home.php). How could I do so that it loads the previous displayed page?
Use local storage for example or sessions.
Local storage example:
$(document).ready(function() {
var lastPage = localStorage['lastPage'];
if (!lastPage) { // If user was on any url before we will exectue goto function
goto(lastPage)
}
function goto(addr) {
localStorage['lastPage'] = addr; // Set url to local storage before load page
$("#content").load(addr);
}
});
not only localStore but you need change the hash of url, and after do one function to catch hash code and execute at you "goto" function...
"something like that"
function hashnav(){
var hashfull = document.location.hash
var hash = hashfull.replace('#', '');
var $page = '';
goto(hash);
}
function changeHash($hash) {
window.location.hash = $hash;
}
function goto(addr) {
changeHash(addr);
}
$(window).bind( 'hashchange', function() {
hashnav();
return false;
});