I'm having an issue trying use local storage values to save a timer on a webpage, navigate to another page, then start the timer again from the values saved from clicking off the initial page.
I have the seconds to work but struggling with the minutes and hours, not sure what I'm doing wrong.
I can input the saved minutes and hours values into the formula, but since the formula dynamically updates every second it doesn't work correctly.
Any help on this would be really appreciated, thanks.
Here is the code:
var secondtime = localStorage.getItem("Seconds");
var minutetime = localStorage.getItem("Minutes");
var hourtime = localStorage.getItem("Minutes");
var sec = localStorage.getItem("Seconds");
setInterval( function(){
document.getElementById("text").innerHTML;
document.getElementById("seconds").innerHTML=pad(++sec%60);
document.getElementById("minutes").innerHTML=pad(parseInt(sec/60,10));
document.getElementById("hours").innerHTML=pad(parseInt(sec/6000,10));
}, 1000);
function SaveTime() {
localStorage.setItem("Seconds", $("#seconds").text())
localStorage.setItem("Minutes", $("#minutes").text())
localStorage.setItem("Hours", $("#hours").text())
}
$(document).ready(function(e) {
$("#seconds").text(secondtime);
$("#minutes").text(minutetime);
$("hours").text(hourtime);
<div class="Bottom_Bar">
<p class="c1" id="seconds_text"><span id="seconds">00</span></p>
<p class="c1" id="minutes_text"><span id="minutes">00</span></p>
<p class="c1" id="hours_text"><span id="hours">00</span></p>
<div class="Button">
<a href="NextPage.html"> onclick="SaveTime()</div>
First thing i'd like to bring to your notice is that you are trying to assign minuts to hourTime variable too take a look at you initialization
var hourtime = localStorage.getItem("Minutes");
And below is the simple code which store and retrieves time from local storage
Save Current Time |
Retrieve Saved Time
<div id="result"></div>
function SaveTime(){
var date = new Date();
var timeObj = { sec:date.getSeconds(), min:date.getMinutes(), hr:date.getHours() };
localStorage.setItem("timeObj", JSON.stringify(timeObj));
$('#result').append(JSON.stringify(timeObj)+' -- > Saved<br />' );
}
function retrieveTime(){
var timeObj = JSON.parse(localStorage.getItem("timeObj"));
//You have the time with you now
$('#result').append(timeObj.hr+':'+timeObj.min+':'+timeObj.sec+' --> Retrieved<br />');
}
Here is JS Fiddle Demo
Related
How can I find a random location based on the moment-timezone.js? I want to show a new location every time you refresh the page.
Current code:
<hero>
<div id="hover">
<h2>Present time</h2>
<div id="time"></div>
</div>
</hero>
<script>
(function clock() {
var now = moment().format('lll'); //local time
/*
I want many of these..
moment.tz("Europe/Berlin").format('lll');
*/
var time = document.getElementById('time');
time.innerHTML = now;
setInterval(clock, 1000);
})();
</script>
You can choose a random timezone from all available timezones:
const timezones = moment.tz.names();
const randTimezone = timezones[Math.floor(Math.random() * timezones.length)];
const now = moment.tz(randTimezone).format('lll');
document.write(randTimezone, '<br>', now);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>
You can get a random timezone by picking off a random element from all timezones.
var all = moment.tz.names();
var randomTimeZone = all[Math.floor(Math.random()*all.length)];
// Use it in the code as
moment.tz(randomTimeZone).format('lll');
I need to show the tipical 'use of cookies' message at the bottom of the page just when some user visits the web, and just show it once at day,I'm trying but my code it's not working properly. here's the code I have so far...
<div id="cookie1"> </div>
<button id="botoncookie">Acept</button>
<script type="text/javascript">
document.getElementById('cookie1').style.bottom = '-50px';
var expiresdate = 5000 ; //1 day
$('#botoncookie').on('click',function(){
var mensaje = document.cookie.split('cookie1=')[1] + expiresdate;
$('#botoncookie').hide();
$('#cookie1').hide();
});
if(mensaje != null){
document.getElementById('cookie1').style.display = 'none';
}else{
document.cookie = 'cookie1=visto;path=/';
}
</script>
Set a cookie with an expiration time of 24*60*60 and whenever a page is loaded, check if the cookie exists, otherwise, display the message.
When your page loads execute the following function. This will check when the cookieMsg was displayed. If already displayed today, no need to display. As a boundary case, for the first time load, it will be null and it will anyway works.
EDIT: In the previous snippet i was just comparing the date which included time as well, you need to specifically check for date only.
function displayMsg(){
var today = new Date();
var lastDisplayedOn = localStorage.getItem('cookieLastDisplayed');
if(lastDisplayedOn){
var ld = new Date(lastDisplayedOn)
if(today.getDate() == ld.getDate() && today.getMonth() == ld.getMonth() && today.getFullYear() == ld.getFullYear()){
donotDisplay()
}else{
displayCookie()
}
}else{
displayCookie()
}
}
I currently have the following code showing:
<h1 id="header1" class="loginhead">Welcome to the <%=formFields.getDisplayValue("programName")%> Registration Site, .</h1>
I need to replace it with:
<h1 id="header2" class="loginhead" >The <%=formFields.getDisplayValue("programName")%> Registration Site, is now closed.</h1>
I need the replace to happen when the date and time are 7/15/15 11:59PM PT
Any way to do this using Jquery, JSP or Javascript?
Update**
<h1 id="header" class="loginhead" ><span id='welcome'></span><span id='welcome2'></span> <%=formFields.getDisplayValue("programName")%> Registration Site <span id='closed'></span> </h1>
<script>
var now = new Date().getTime(); //Return the number of milliseconds since 1970/01/01:
var epochTimeJul15_1159pm = 1437019199000; // number of milliseconds since 1970/01/01 at Jul 15_11:59:59pm. See http://www.epochconverter.com/.
var timeTillChange = epochTimeJul15_1159pm - now;
function changeHeader(){
document.getElementById('closed').innerHTML = ' is now closed.'; //change the html/text inside of the span with the id closed'.
}
function changeHeader1()
{
if(epochTimeJul15_1159pm <= now)
{
document.getElementById('welcome').innerHTML = 'The ';
}
}
function changeHeader2()
{
if(now < epochTimeJul15_1159pm)
{
document.getElementById('welcome2').innerHTML = 'Welcome to the ';
}
}
setTimeout(changeHeader, timeTillChange); //will wait to call changeHeader function until timeTillChange milliseconds have occured.
setTimeout(changeHeader1, timeTillChange);
setTimeout(changeHeader2, timeTillChange);
</script>
First make it easier to use javascript to edit your html. We will do this by creating an empty span to insert the closed message into:
<h1 id="header" class="loginhead" >Welcome to the <%=formFields.getDisplayValue("programName")%> Registration Site <span id='closed'></span> </h1>
Now in your javascript section:
var now = new Date().getTime(); //Return the number of milliseconds since 1970/01/01:
var epochTimeJul15_1159pm = 1437019199000; // number of milliseconds since 1970/01/01 at Jul 15_11:59:59pm. See http://www.epochconverter.com/.
var timeTillChange = epochTimeJul15_1159pm - now;
function changeHeader(){
document.getElementById('closed').innerHTML = ' is now closed.'; //change the html/text inside of the span with the id closed'.
}
setTimeout(changeHeader, timeTillChange); //will wait to call changeHeader function until timeTillChange milliseconds have occured.
This will make the header get edited live as soon as the clock hits 11:59:59.
if ($.now >= dateLimit){
$("#header1").hide(0);
$("#header2").show(0);
}
This would be a general jquery way to do this, you could setup the two elements to be hidden or shown accordingly in your css.
This would do it upon page load, I am not exactly sure how to implement a dynamic version of this.
That's how you can do dynamically with JavaScript. Working Plunker
You can just compare two date and change innerHTML of header.
<html>
<head>
<script>
function setHeader(){
var d1 = new Date("7/15/15 11:57"); // change your dates here
var d2 = new Date("7/15/15 11:58"); // change your dates here
var header = document.getElementById("header");
if(d1 > d2){
header.innerHTML = "Welcome to the " + <%=formFields.getDisplayValue("programName")%> + " Registration Site."
} else {
header.innerHTML = "Welcome to the " + <%=formFields.getDisplayValue("programName")%> + " Registration Site, is now closed. "
}
}
</script>
</head>
<body onload="setHeader()">
<h1 id="header" class="loginhead"></h1>
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<title>Zautra Levels</title>
<h2 style="font-family: Trebuchet MS; color: blue;"">Zautra Levels</h2>
<p> </p>
</head>
<body>
<p>Clickables:</p>
<button id="swag" onclick="lmao()">Gain XP</button> <button id="gold" onclick="getgold()">Get Gold</button> <button id="buyupgrade" onclick="buyupp()">Level Up!</button>
<p> </p>
<div id="total">XP: 0</div>
<div id="goldt">Gold: 0</div>
<div id="upgradess">Level: 0</div>
<div id="upcostt">Required XP: 25</div>
<script>
var clicks = 0; // How many clicks you have
var upgrades = 0; // How many upgrades you have purchased
var upcost = 25; // How much the upgrades cost
var gold = 0; // How much gold you have
function updateclicks() { // Declares the function that updates the "Zautra Clicks" Text.
var v=document.getElementById("total");
v.innerHTML = 'XP: ' + clicks;
}
function updategold() { // Declares the function that updates the "Zautra Clicks" Text.
var g=document.getElementById("goldt");
g.innerHTML = 'Gold: ' + gold;
}
function updateupgradecounter() { // Declares the function that updates the "Upgrades:" Text.
var y=document.getElementById("upgradess");
y.innerHTML = 'Level: ' + upgrades;
}
function updateupcost() { // Declares the function that updates the "Upgrade Cost:" Text.
var z=document.getElementById("upcostt");
z.innerHTML = 'Required XP:' + upcost;
}
var x=document.getElementById("swag"); function lmao() { // When you click the "Click for MOAR Zautra's" Button you get a +1 Click.
clicks+=1;
updateclicks();
}
var j=document.getElementById("gold"); function getgold() { // When you click the "Click for MOAR Zautra's" Button you get a +1 Click.
gold+=1;
updategold();
}
var c=document.getElementById("buyupgrade"); function buyupp() {
if (clicks >= upcost) {
clicks-=upcost
upgrades+=1
upcost*=2
updateclicks();
updateupgradecounter();
updateupcost();
}
else
{
var clicksdif = upcost - clicks;
confirm("You need " + clicksdif + " more XP to level up.");
}
}
</script>
</body>
</html>
This is the code for my game that I am working on.
I'm trying to add a button, and when you press it, it saves all of the variables.
If you're level 5 with 26 XP, and 7 gold, you refresh the page, you still have those stats instead of losing them on refresh.
Please help!
(And yeah, I do realize that the code is really messed up, but that is a small issue. I'll fix that sooner or later.)
I believe that actually the easiest way, easier than cookies, is to pass the values via the URL. Example:
<form action="yourPage.php?gold=$amount&level=$whatlevel&experience=$experience" method="POST">
//Your refresh button here
</form>
and then to retrieve those variables when the page reloads, use: gold=$_POST['gold']
Another option as well is to use the GET method instead of POST.
Keep in mind that the file extension needs to be php for this code to work.
you could create a cookie in php:
setcookie("NameOfTheCookie",$value,$expireTime)
and $value can be an array of values as well.
I'm trying to get three different dynamic timezone clocks on my site. i've got the following js code which i found on this site (saved as myClocks.js and included on the header of my html site):
var clock1 = new Date();
var clock2 = new Date();
var clock3 = new Date();
clock2.setHours(clock2.getHours() + 3);
clock3.setHours(clock3.getHours() - 5);
clock1.getUTCHours();
clock1.getUTCMinutes();
clock1.getUTCSeconds();
clock2.getUTCHours();
clock2.getUTCMinutes();
clock2.getUTCSeconds();
clock3.getUTCHours();
clock3.getUTCMinutes();
clock3.getUTCSeconds();
How do I code the "display" to show it anywhere I want on my HTML page? For example as an id called clocks, to look like the following:
New York: 02:12:02 Paris: 17:01:24 Moscow: 22:23:42
Many thanks in advance.
<html><head></head><body>
<script language="javascript">
ourDate = new Date();
document.write("The time and date at your computer's location is: "
+ ourDate.toLocaleString()
+ ".<br/>");
document.write("The time zone offset between local time and GMT is "
+ ourDate.getTimezoneOffset()
+ " minutes.<br/>");
document.write("The time and date (GMT) is: "
+ ourDate.toGMTString()
+ ".<br/>");
</script>
</body></html>
innerHTML is what you need. Try something like:
window.onload = function(){ // It is important to wait till DOM is ready!
var clocks_str = clock3.getUTCHours()+" "+ clock3.getUTCMinutes()+" "+clock3.getUTCSeconds();
document.getElementById("clocks").innerHTML = clocks_str ;
}
And if you want it dynamic , use setInterval method , like this:
var clocks_interval;
var clocks_box;
window.onload = startClocks;
function startClocks(){
clocks_box = document.getElementById("clocks");
clocks_interval = setInterval(updateClocks , 1000); // 1000 means 1 second
}
function updateClocks (){
var clocks_str = clock3.getUTCHours()+" "+ clock3.getUTCMinutes()+" "+clock3.getUTCSeconds();
clocks_box.innerHTML = clocks_str ;
}
You can create a div or other HTML and use "innerHTML".
document.getElementById("clocks").innerHTML = clock1.getUTCHours();