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);
Related
Currently I'm trying to create a quiz, right now it displays the first question with 4 answer choices after the start button I am stuck on how to retrieve the answer. The user clicks, check to see if its correct and loop to the next question. I just want to give the user one chance per question and move on regardless if it's correct or not. If their answer is wrong I will remove seconds from the timer. I have the questions, answer choices, and correct answers in arrays.
<div class="card-body">
<p id="header">
You have 75 seconds to complete this asessment.
Every incorrect answer will cost you time.
<br>
</p>
<button id="start-button" class="btn">Start</button>
<div id="start-game" style="visibility: hidden">
<button id="option0" data-index="0"></button><br>
<button id="option1" data-index="1"></button><br>
<button id="option2" data-index="2"></button><br>
<button id="option3" data-index="3"></button><br>
</div>
</div>
<script src="./script.js"></script>
var timerEl = document.getElementById("timer");
var start = document.getElementById("start-button");
var questionEl = document.getElementById("header");
var option0 = document.getElementById("option0");
var option1 = document.getElementById("option1");
var option2 = document.getElementById("option2");
var option3 = document.getElementById("option3");
var intials = document.getElementById("user-initials");
var buttonEl = document.getElementById("start-game");
var totalTime = 75;
var elapsedTime = 0;
var questionNum = 0;
var questions =["The condition in an if/else statement is enclosed with in _______",
"Arrays in JavaScript can be used to store ______",
"Commonly used data types do not include ______",
"String values must be enclosed within _____ when being assigned to variables"];
var answers =[question1= ["Quotes","Curly brackets","Parentheses","Square brackets"],
question2= ["Numbers and strings","Other arrays","Booleans","All of the above"],
question3= ["Strings","Booleans","Alerts","Numbers"],
question4= ["Commas","Curly brackets","quotes","parentheses"],
];
var correctAnswers = [2,3,2,2];
start.addEventListener("click", function(){
timer();
displayQuestion();
start.style.visibility = "hidden";
buttonEl.style.visibility = "visible";
});
function timer(){
var timerInterval = setInterval(function(){
totalTime --;
timerEl.textContent = totalTime;
if(totalTime === 0){
clearInterval(timerInterval);
endQuiz();
return;
}
}, 1000);
}
function newQuiz(){
questionEl.textContent = (questions[0]);
};
function displayQuestion(){
for( var i = 0; i < questions.length ; i++){
questionEl.textContent=(questions[i]);
option0.textContent=(answers[i][0]);
option1.textContent=(answers[i][1]);
option2.textContent=(answers[i][2]);
option3.textContent=(answers[i][3]);
console.log(i);
return;
}
}
Hi I will try to provide an easy solution to your question without using any kind of difficult javascript syntax so here goes..
First in your html file update the option button and add a class property called clickOption(you can change the class name if you want, but be sure to change in other places in script.js as well). The code is shown below.
<button id="option0" class="clickOption" data-index="0"></button><br>
<button id="option1" class="clickOption" data-index="1"></button><br>
<button id="option2" class="clickOption" data-index="2"></button><br>
<button id="option3" class="clickOption" data-index="3"></button><br>
Now in your script.js file add the line of code shown below. I have added inline comments for better understanding
// get all elements with class clickoption i.e all option buttons
var elements = document.getElementsByClassName("clickOption");
//use the below array to track the selected answers
var selectedAnswers = [];
var clickOption = function() {
/** Here I have reached the end of the test and,
I am logging the array of user-selected options.
This array can be compared with correctAnswers array
to determine whether the answer is correct or not **/
if(questionNum >= questions.length) {
console.log(selectedAnswers);
return;
}
/**Get the option value that was clicked.
Here I am using parseInt because,
the data-index attribute value will be in string format,
and the correctAnswers array is in Number format so it is better,
to keep the selectedAnswers array in Number format as it will faciliate
easier data comparison**/
var selectedOption = parseInt(this.getAttribute('data-index'));
// add the selected option to the selectedAnwsers Array
selectedAnswers.push(selectedOption);
/** here I am assuming that you are using the questionNum variable
to track the current question Number **/
questionNum += 1;
/** here I am again checking if I have reached the end of test and
thus log the answers
Instead of logging the answer you can create a function
that compares the result and display it on screen **/
if(questionNum >= questions.length) {
console.log(selectedAnswers);
return;
}
// update the next question text
questionEl.textContent = questions[questionNum];
// update next options
displayQuestion(questionNum);
}
//loop through all the elements with class clickOption
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', clickOption);
}
start.addEventListener("click", function() {
timer();
/** I have updated the displayQuestion call implementation
so that the function is called with a parameter
(here the parameter it is zero) **/
displayQuestion(questionNum);
start.style.visibility = "hidden";
buttonEl.style.visibility = "visible";
});
/**Finally I have updated the display question method
so that it updates the option buttons based on the index parameter **/
function displayQuestion(index){
questionEl.textContent = questions[index];
option0.textContent = answers[index][0];
option1.textContent = answers[index][1];
option2.textContent = answers[index][2];
option3.textContent = answers[index][3];
}
Hope this solution helps you. Happy Coding!
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.
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)
Well, my code have been working fine and I'm simply trying to make a simple game, until I added this (due to that I wanted to learn how to save the info to the users local storage):
if(localStorage.getItem('money'))
{
var Money = localStorage.getItem('money');
document.getElementById('test').innerHTML="EXISTS";
} else {
localStorage.setItem('money', 0);
var Money = localStorage.getItem('money');
document.getElementById('test').innerHTML="DOES NOT EXIST";
}
My full code looks like this:
<head><meta charset="UTF-8"></head>
<body><span id='test'></span>
Generated something: <span id='money'>0$</span> (money per click: <span id='MPC'>1$</span>)
<br />
Upgrade 1 upgrades: <span id='u1Us'>0</span> (production rate: <span id='u1Pr'>0</span>)
<br />
<span id='updates'></span>
<br />
<button onClick='mButton()'>Generate something.</button>
<br /><br />
<b>Upgrades:</b>
<br /><br />Generator upgrades:<br />
<button onClick='buyU1()'>Buy upgrade 1. ($30)</button>
<br /><br />Self-generated upgrades:<br />
<button onClick='buySG1()'>Buy Self-Generated Upgrade 1 ($500)</button>
</body>
<script>
if(localStorage.getItem('money'))
{
var Money = localStorage.getItem('money');
document.getElementById('test').innerHTML="EXISTS";
} else {
localStorage.setItem('money', 0);
var Money = localStorage.getItem('money');
document.getElementById('test').innerHTML="DOES NOT EXIST";
}
var U1Amount = 0;
var cMoney = 1;
function mButton()
{
Money += cMoney;
document.getElementById('money').innerHTML=Money + "$";
}
function buyU1()
{
if(Money < 30)
{
document.getElementById('updates').innerHTML="You do not have enough money.";
resetUpdates();
} else {
Money -= 30;
U1Amount += 1;
document.getElementById('u1Us').innerHTML=U1Amount;
document.getElementById('money').innerHTML=Money + "$";
document.getElementById('updates').innerHTML="You have successfully bought Upgrade 1";
var calcU1Amount = U1Amount * 5;
document.getElementById('u1Pr').innerHTML=calcU1Amount;
resetUpdates();
}
}
var interval = setInterval(gMoneyU1, 1000);
function gMoneyU1()
{
var calc = 5 * U1Amount;
Money += calc;
document.getElementById('money').innerHTML=Money + "$";
}
function buySG1()
{
if(Money < 500)
{
document.getElementById('updates').innerHTML="You do not have enough money.";
resetUpdates();
} else {
Money -= 500;
cMoney += 1;
document.getElementById('MPC').innerHTML=cMoney + "$";
document.getElementById('money').innerHTML=Money;
}
}
function resetUpdates()
{
setTimeout(function(){document.getElementById('updates').innerHTML="";}, 10000);
}
</script>
I'm going to add the localStorage to all info that I want to save, but I'm having problems with the first one so yer.
What my code WITH my save-the-persons-info outputs is: http://puu.sh/6iONl.png (and it keeps on in all eternally)
It keeps adding '0' for some reason and I can't figure out why. I'd really appreciate help.
Thanks in advance.
Sorry if my code is messy, I'm still learning, hence why asking for help.
The only time that you ever set to localStorage is when you call localStorage.setItem('money', 0);.
You probably want to change that to setting the real value of the money variable.
Local storage stores everything as a string, so you'll want to call parseInt() on whatever you get back from local storage. Then, you should be able to properly add two ints together, rather than concatenating two strings together.
The values in localStorage are all strings. When you do:
localStorage.setItem('x', 0);
var x = localStorage.getItem('x'); // x === '0'
x = x + 1; // x = '01';
the thing you set in local storage will be the value you gave converted to a string. You should parseInt (or convert it some other way back to a number) when you retrieve it from localStorage to avoid this problem.
Your if statement will always return false so you'll never get to the "if true" part of your if statement. This is because the local storage value will either be null if not set, or a string value ("0") on most browsers if set, or an integer on some browsers if set. (Most browsers will only maintain strings for local storage, although the HTML5 specs do allow for other values.)
So first, of you would need to change the if part to something like this:
if (localStorage.getItem('money') != null)
I'm not completely sure what you're trying to achieve logic-wise but as mentioned, your other issue is that you're only setting the value to 0 and then reading the value right after (which would be zero still.) This is why you're getting zeros.
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;
}