I have a small web calculator which calculates time. My mobile browser gets rid of all data when I've minimised/closed the mobile broswer for a few minutes or on a page refresh so I've made a button which can reload all previous data and displays as text.
I want to get rid of the "Get old data" button and just have the page reload with all the values displayed in the input box as they were before the page refresh.
I've been thinking an onload event in the input box would work but as i understand this is not possible.
HTML
<body onload="getreload()">
<p>Please enter minutes</p>
<input type="text" id="etime">
<br>
<p>Please enter time in 24 hour format (eg. 15:00)</p>
<input type="text" id="stime">
<br>
<br>
<button onclick="myFunction()">Calculate</button>
<p id="finishtime">
<br>
<br>
<button onclick="getreload()">Get old data</button>
<p id="finishtime2">
<p id="mintime2">
</body>
Javascript
function myFunction() {
function converToMinutes(s) {
var c = s.split(':');
return parseInt(c[0]) * 60 + parseInt(c[1]);
}
function parseTime(s) {
var seconds = parseInt(s) % 60;
return Math.floor(parseInt(s) / 60) + ":" + ((seconds < 10)?"0"+seconds:seconds);
}
var endTime = document.getElementById("etime").value;
var startTime = converToMinutes(document.getElementById("stime").value);
var converted = parseTime(startTime - endTime);
document.getElementById('finishtime').innerHTML = "You will finish your break at " + converted;
if (typeof(Storage) !== "undefined") {
localStorage.setItem("convertedTime", converted);
localStorage.setItem("endTimeReload", endTime);
} else {
// Sorry! No Web Storage support
}
}
function getreload() {
var convertedTime = localStorage.getItem("convertedTime");
document.getElementById('finishtime2').innerHTML = "End of break time: " + convertedTime;
var endTimeReload = localStorage.getItem("endTimeReload");
document.getElementById('mintime2').innerHTML = "Minutes till next client: " + endTimeReload;
}
You are mostly there, but you are not restoring correctly and not saving the startTime.
Here is a fiddle with everything you need:
https://jsfiddle.net/22ej8scw/
Restore like this. (I also changed how it is saved)
function getreload() {
var startTime = localStorage.getItem("startTime");
document.getElementById("stime").value = startTime;
var endTimeReload = localStorage.getItem("endTimeReload");
document.getElementById("etime").value = endTimeReload;
if (startTime && endTimeReload)
myFunction();
}
So after you've calculated a time, you want those values to be there if you refresh the page?
When you calculate, save all the values in localstorage, then when the page loads (body element's 'onload') set the input boxes values to the corresponding localstorage ones (checking to make sure those values exist first)
Related
I am currently having a problem displaying a calculated sum on the next page in javascript/html.
My calculation for defining the sum looks like this, where the 'sum + €' is displayed at the end.
function udregnPant() {
let sum = 0;
for (i = 0; i <= pantListParsed.length; i++) {
let totalPantKr = pantListParsed[i].aPantMoney + pantListParsed[i].bPantMoney + pantListParsed[i].cPantMoney;
sum += totalPantKr;
console.log(sum);
document.getElementById('sumAfPantB').innerHTML = sum + " €.";
}
}
In the following HTML input I want to display the sum as the value instead of '10 €'
<input type="text" name="amount" id="text1" value="10 €." readonly/>
Appreciate your help!
Make use of web storage.
sessionStorage - stores data for one session
sessionStorage.getItem('label')
sessionStorage.setItem('label', 'value')
localStorage - stores data with no expiration date
localStorage.getItem('label')
localStorage.setItem('label', 'value')
Example
function setSum(value) {
localStorage.setItem("sum", value);
}
function getSum() {
return localStorage.getItem("sum");
}
Live Example at JS Bin
References
Share data between html pages
HTML5 Web Storage
After calculating your value, redirect the user to a URL with the value in the query string (See Redirections in HTTP) -- this may look something like
window.location = http://mysite/page2.html?amount=12
On the new page, retrieve the value from the query string using the searchParams property (see URL.searchParams). Could look something like:
let params = (new URL(document.location)).searchParams;
document.getByElementId('text1').value = params.get('amount');
Here is a little example using local Storage, since so doesnt allow local storage try it in jsfiddle and
the code sample as well:
document.getElementById('btnSend').onclick = ()=>{
let total = document.getElementById('txtTotal').value;
if(!isNaN(total) && total > 0){
localStorage.setItem('total', total);
document.getElementById('txtTotal').value = '';
}
}
document.getElementById('btnLastTotal').onclick = ()=>{
var lastTotal = localStorage.getItem('total');
if(lastTotal !=undefined){
alert('last total is:'+lastTotal);
}else{
alert('No records found');
}
}
<input type="text" id="txtTotal">
<br>
<input type="button" id="btnSend" value="Save the total"> <input type="button" id="btnLastTotal" value="get Last Total">
Hope it helps
I have a little problem, I repeat timepicker with *ngFor, but it's not working properly if I changed the time in one of them, it changes in all. And all have a different id. AN IDEA TO MAKE THE WORk PROPERLY?`
COMPONENT.HTML :
<div id="schedule" *ngFor="let i of Arr(num).fill(1)"
style="display: -webkit-inline-flex">
<timepicker id="timer" class="schedulItem" style="margin-top:-28px"
[(ngModel)]="mytime" [showMeridian]="isMeridian"
[minuteStep]="mstep" (ngModelChange)="changed()">
</timepicker>
<button (click)="addSchedule()"> + </button>
</div>
COMPONENT.TS:
Arr = Array; //Array type captured in a variable
num:number = 1;
mytime: Date;
addSchedule() {
this.num = this.num + 1 ;
var length = document.querySelectorAll('.schedul').length
var time = document.getElementById("timer");
time.id += length;
}
changed(): void {
var time = this.mytime.getHours() + ":" + this.mytime.getMinutes();
console.log(time);
}
I found the problem! the model was the problem [(ngModel)]="mytime". All time pickers to the same model and one gets changed it changes all of them.
This has to be super easy, just couldn't find the solution for the past three hours:
I want to display a number (100) on my website that will be increased by the days past, problem is that the number goes back to the 100 when I reload the website, how do I make that number stay increased over time?
Here's the code:
<script>
var smyle = 11406;
var happyclients = 1006;
var hours = 4220;
window.setInterval(
function () {
smyle = smyle + 2;
document.getElementById("smiles").innerHTML = smyle;
}, 2880);
window.setInterval(
function () {
happyclients = happyclients + 4;
document.getElementById("happy").innerHTML = happyclients;
}, 28800000);
window.setInterval(
function () {
hours = hours + 8
document.getElementById("hoursspent").innerHTML = hours;
}, 86400000);
</script>
The HTML
<div class="col-md-3 col-sm-6 animate-box" data-animate-effect="fadeInLeft">
<div class="feature-center">
<span class="icon">
<i class="ti-music"></i>
</span>
<span class="counter js-counter" data-from="0" data-to="" data-speed="4000" data-refresh-interval="50" id="smiles"></span>
<span class="counter-label">Smiles Created</span>
</div>
</div>
I am new to JS, previously tried with PHP but couldn't find the answer either, this is the closest I got.
So far I've gotten to this with your help, the idea of storing the data on the local database is quite clean and efficient, but I'm not being able to make it work yet (see changes at the bottom of the code)
I've read plenty of documentation about this and I think that the order is correct, but is it?
<script>
var smyle = 11000;
var happyclients = 1006;
var hours = 4220;
window.setInterval(
function () {
smyle = smyle + 2;
document.getElementById("smiles").innerHTML = smyle;
}, 288);
window.setInterval(
function () {
happyclients = happyclients + 4;
document.getElementById("happy").innerHTML = happyclients;
}, 288);
window.setInterval(
function () {
hours = hours + 8
document.getElementById("hoursspent").innerHTML = hours;
}, 864);
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("smyle");
//Retrieve
document.querySelector("smiles").innerHTML = localStorage.getItem("smyle");
} else {
document.write(11404);
}
</script>
I didn't change anything in the HTML part yet, so the id is still id="smiles"
You may wish to store this somewhere, which could be a cookie or more easily just store it in a database. You can say for each user how long they have spent, by updating your database every few seconds or minutes. Then all you would need to do is pull for that data and check where the data is.
Currently, your method requires the user to have the page open continuously, which will in fact restart it every time as the JavaScript will have no sense of previous time spent.
you can save it in localStorage on client side.
here is the reference
if you want the same result for everyone you should do this on your server.
Saving the data in localStorage will definitely help:
localStorage.setItem(//takes an object);
For retrieval:
document.querySelector("...").innerHTML = localStorage.getItem(//takes object key);
I am the new administrator of a website I did not created (professionnals did, I'm just an IT student beginning with JavaScript). I wanted to add a timer on the homepage of the website with the following working code I founded on the Internet:
<script language="JavaScript1.2">
//##################################################
// Author: ricocheting.com
// For: public release (freeware)
// Date: 4/24/2003 (update: 6/26/2009)
// Description: displays the amount of time until the "dateFuture" entered below.
// NOTE: the month entered must be one less than current month. ie; 0=January, 11=December
// NOTE: the hour is in 24 hour format. 0=12am, 15=3pm etc
// format: dateFuture = new Date(year,month-1,day,hour,min,sec)
// example: dateFuture = new Date(2003,03,26,14,15,00) = April 26, 2003 - 2:15:00 pm
dateFuture = new Date(2014,10,25,20,00,00);
// TESTING: comment out the line below to print out the "dateFuture" for testing purposes
//document.write(dateFuture +"<br />");
//###################################
//nothing beyond this point
function GetCount(){
dateNow = new Date(); //grab current date
amount = dateFuture.getTime() - dateNow.getTime(); //calc milliseconds between dates
delete dateNow;
adversaire = "Saastal";
// time is already past
if(amount < 0){
document.getElementById('countbox').innerHTML="Le match Sion - " + adversaire + " a débuté !";
}
// date is still good
else{
days=0;hours=0;mins=0;secs=0;out="";
amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs
days=Math.floor(amount/86400);//days
amount=amount%86400;
hours=Math.floor(amount/3600);//hours
amount=amount%3600;
mins=Math.floor(amount/60);//minutes
amount=amount%60;
secs=Math.floor(amount);//seconds
if(days != 0){out += days +" jour"+((days!=1)?"s":"")+", ";}
if(days != 0 || hours != 0){out += hours +" heure"+((hours!=1)?"s":"")+", ";}
if(days != 0 || hours != 0 || mins != 0){out += mins +" minute"+((mins!=1)?"s":"")+", ";}
out += secs +" seconde"+((secs!=1)?"s":"");
document.getElementById('countbox').innerHTML="Temps restant avant Sion - " + adversaire + " : " + out;
setTimeout("GetCount()", 1000);
}
}
window.onload=GetCount;//call when everything has loaded
</script>
<div id="countbox"></div>
The only problem is that when I add this code (which works), then another JavaScript code already on the page (scrolling text) doesn't work anymore. Here is the code of the scrolling text but what is important is that I founded it with "Right click/view page source" and I cannot change it, except for the text part (in the admin page, I have a textbox in which I write the text that is going to scroll and according to the following code, this text is just a variable part of the JavaScript function) :
<h3 class="replace">Agenda</h3>
<script language="JavaScript1.2">
// Distributed by http://www.hypergurl.com
// Scrollers width here (in pixels)
var scrollerwidth="180px";
// Scrollers height here
var scrollerheight="100px";
// Scrollers speed here (larger is faster 1-10)
var scrollerspeed=1;
/* Scrollers content goes here! Keep all of the message on the same line!
* var scrollercontent='<font face="Arial" color="green" size="5">
* <b>Place your content here.<br>
* vous pouvez inclure des balises HTML, des hyperliens
* Script distributed by Hypergurl.com.
* The scrolling massage will now pause on mouseover.<br>
* Thanks David for the update!</b></font>'
* le texte de la marquee doit être inclu dans une balise <div> ... </div>
* ATTENTION: les aphostrophes doivent impérativement être échappés!!!!
*/
var txt = ' '
+ 'HERE IS THE TEXT I CAN WRITE'
var scrollercontent = ''
+ txt
+ '';
var pauseit=1;
// Change nothing below!
scrollerspeed=(document.all)? scrollerspeed : Math.max(1, scrollerspeed-1) //slow speed down by 1 for NS
var copyspeed=scrollerspeed
var iedom=document.all||document.getElementById
var actualheight=''
var cross_scroller, ns_scroller
var pausespeed=(pauseit==0)? copyspeed: 0
function populate(){
if (iedom){
cross_scroller=document.getElementById? document.getElementById("iescroller") : document.all.iescroller
cross_scroller.style.top=parseInt(scrollerheight)+8+"px"
cross_scroller.innerHTML=scrollercontent
actualheight=cross_scroller.offsetHeight
}
else if (document.layers){
ns_scroller=document.ns_scroller.document.ns_scroller2
ns_scroller.top=parseInt(scrollerheight)+8
ns_scroller.document.write(scrollercontent)
ns_scroller.document.close()
actualheight=ns_scroller.document.height
}
lefttime=setInterval("scrollscroller()",50)
}
window.onload=populate
function scrollscroller(){
if (iedom){
if (parseInt(cross_scroller.style.top)>(actualheight*(-1)+8))
cross_scroller.style.top=parseInt(cross_scroller.style.top)-copyspeed+"px"
else
cross_scroller.style.top=parseInt(scrollerheight)+8+"px"
}
else if (document.layers){
if (ns_scroller.top>(actualheight*(-1)+8))
ns_scroller.top-=copyspeed
else
ns_scroller.top=parseInt(scrollerheight)+8
}
}
if (iedom||document.layers){
with (document){
if (iedom){
write('<div style="position:relative;width:'+scrollerwidth+';height:'+scrollerheight+';overflow:hidden" onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=scrollerspeed">')
write('<div id="iescroller" style="position:absolute;left:0px;top:0px;width:100%;">')
write('</div></div>')
}
else if (document.layers){
write('<ilayer width='+scrollerwidth+' height='+scrollerheight+' name="ns_scroller">')
write('<layer name="ns_scroller2" width='+scrollerwidth+' height='+scrollerheight+' left=0 top=0 onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=scrollerspeed"></layer>')
write('</ilayer>')
}
}
}
So my question is: do you know a way to let these two JavaScript functions work on the same page? I just want to have my timer either on the homepage, either in the scrolling text (which is also on the homepage, in the right column)...
Thank you in advance for you help.
Kinds regards,
user3507737
It looks like you're overwriting the first script's window.onload call by including the second script, which has its own .onload call.
I would remove the two lines that begin with window.onload from the scripts included above, and add a third <script> tag in your page that does the following:
window.onload = function () {
GetCount();
populate();
};
This should get both your scripts running.
You assign an action to the window.onload event twice. In the first block of javascript you have window.onload=GetCount; and in the second you have window.onload=populate (which needs a semicolon at the end, by the way).
You can only assign one function to the onload event, so it would be best to make a function that calls both GetCount and populate and assign this new function to your window.onload. See more in this answer.
You need to remove the current code that binds to onload and replace it with something like:
window.onload = function () {
populate();
GetCount();
};
I have a pure html+JavaScript slideshow I am making. The slideshow is in a sidebar of the website that is loaded with php for each page that has the slideshow sidebar. The only page without the sidebar is the main page.
The slide show is working fine. However, understandably, each time I go to a new page with the sidebar, the slideshow starts over. Makes sense since the javascript reloads with each new page.
I would like to find some way to have the slideshow remember its place so that when I go to a new page the slide show just continues where it left off on the previous page. I can only think of two solutions, one seem brute force, and one I don't know how to do:
Write the current image number to a file and read it each time the
slideshow loads.
Somehow use ajax, but I haven't learned to use ajax
yet (would it work?).
Any suggestions? Oh, and please I'm learning javascript, jQuery and ajax are next, but...
Here is my code:
simpleslideshow.html:
<html>
initializeSlideShow();
<table width="100">
<tr>
<td align="left"> <div id="previous"> Previous</div></td>
<td align="right"> <div id="next">Next</div></td>
<td align="right"> <div id="auto">auto</div></td>
<td align="right"> <div id="stop">stop</div></td>
</tr>
</table>
<img src="" id="slideshow-image" width="400px" height="auto" style="display:block;"/>
simpleslideshow.js:
var inaterval_ID = 0;
var image_number = 0;
var num_images = images_with_captions.length;
function change_image(increment){
image_number = image_number + increment;
image_number = (image_number + num_images) % num_images;
var string = images_with_captions[image_number].source;
document.getElementById("slideshow-image").src = string;
}
function initializeSlideShow() {
//var string = images_with_captions[0].source;
//document.getElementById("slideshow-image").src = string;
auto();
}
function auto() {
interval_ID = setInterval("change_image(1)", 1000);
}
function stop() {
clearInterval(interval_ID);
}
image_caption_list.js:
var images_with_captions = new Array(
{
source: "http://www.picgifs.com/clip-art/flowers-and-plants/flowers/clip-art-flowers-435833.jpg",
caption: "flower 1"
},
{
source: "http://www.picgifs.com/clip-art/flowers-and-plants/flowers/clip-art-flowers-511058.jpg",
caption: "flower 2"
},
{
source: "http://www.picgifs.com/clip-art/flowers-and-plants/flowers/clip-art-flowers-380016.jpg",
caption: "flower 3"
}
);
Edit: I can't get a jsfiddle to work. But here is a live version that may or may not be up for a while:
You can save the current slide value to either a cookie or localStorage each time you change to a new slide and then when you start up the slideshow on a new page, you can read the previous slide value and start from that slide number.
Here's reading the previous slide number:
function initializeSlideShow() {
// get prior slideshow num
var lastSlideNum = +readCookie("lastSlideNum");
// if there was a prior slideshow num, set that as the last one we used
if (lastSlideNum) {
image_number = lastSlideNum;
}
auto();
}
Here's saving the slideshow number each time it changes:
function change_image(increment){
image_number = (image_number + increment) % num_images;
// remember what slide we're on for subsequent page loads
createCookie("lastSlideNum", image_number);
var string = images_with_captions[image_number].source;
document.getElementById("slideshow-image").src = string;
}
And, here's a simple cookie library:
// createCookie()
// name and value are strings
// days is the number of days until cookie expiration
// path is optional and should start with a leading "/"
// and can limit which pages on your site can
// read the cookie.
// By default, all pages on the site can read
// the cookie if path is not specified
function createCookie(name, value, days, path) {
var date, expires = "";
path = path || "/";
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=" + path;
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
A localStorage implementation (which would not remember the slide in IE versions before IE8) would look like this:
function initializeSlideShow() {
// get prior slideshow num
var lastSlideNum;
// localStorage requires IE8 or newer
// if no localStorage, then we just don't remember the previous slide number
if (window.localStorage) {
lastSlideNum = +localStorage["lastSlideNum"];
// if there was a prior slideshow num, set that as the last one we used
if (lastSlideNum) {
image_number = lastSlideNum;
}
auto();
}
Here's saving the slideshow number each time it changes:
function change_image(increment){
image_number = (image_number + increment) % num_images;
// remember what slide we're on for subsequent page loads
if (window.localStorage) {
localStorage["lastSlideNum"] = image_number;
}
var string = images_with_captions[image_number].source;
document.getElementById("slideshow-image").src = string;
}