How to have a variable not reset when refreshing my website - javascript

<script>
var sum = 0;
var pressYet = false;
function changeIt() {
if(pressYet == false){
sum++;
document.getElementById('test').innerHTML = sum;
pressYet = true;
} else {
document.getElementById('test').innerHTML = "You have already pressed the button";
document.getElementById("button").style.visibility = "hidden";
}
}
</script>
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()" id = "button" >Press If you are here</button>
SO I have this sweet epic button on my website, its very cool, but I want to make it better. I was wondering how to make the variable 'sum' not reset every time I refresh my website. I know there's a term for that but for the life of me I cannot figure it out. I want it so every time someone presses the button, 'sum' gets added one to it and that number would be permanent. So over time that number gets very large.
I am very new to HTML so please be kind to me.

You can save the value to localStorage and then retrieve it from localStorage after page load. Then on the basis of the data you can adjust the page. I have slightly modified your code here
var sum = 0;
var pressYet = localStorage.getItem('pressYet');
function changeIt() {
if (pressYet == null) {
sum++;
document.getElementById('test').innerHTML = sum;
pressYet = true;
localStorage.setItem('pressYet', pressYet);
} else {
document.getElementById('test').innerHTML = "You have already pressed the button";
document.getElementById("button").style.visibility = "hidden";
}
}
(function init() {
if (localStorage.getItem('pressYet') != null || localStorage.getItem('pressYet') != "") {
document.getElementById('test').innerHTML = "You have already pressed the button";
document.getElementById("button").style.visibility = "hidden";
}
})();
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()" id="button">Press If you are here</button>
You can check out the demo https://jsfiddle.net/5jyrk6s8/

Related

make text disappear after clicking another clickable object

I am making an escape room for my website, I have made a few clickable objects that will display a text. My question is, how do I make text go away after clicking on another clickable item? Everything else in my code works just how I like it except for the text part. Please help
Here is what I have so far.
var hasBluekey = false;
var doorknob = "locked"
var comboLock = "locked"
function tryDoor() {
console.log("You clicked the door");
}
function lookhelp() {
console.log("You clicked on help");
let text = "Who needs help?";
document.getElementById("thehelp").innerHTML = text;
}
function lookClue() {
console.log("You clicked on the clue");
let text = "Hmm, there are letters and numbers circled...";
document.getElementById("theclue").innerHTML = text;
}
function moveTable() {
console.log("You clicked on the table");
let text = "You carefully move away the table with the broken vase";
document.getElementById("thetable").innerHTML = text;
document.getElementById("table").style.display = "none";
}
function tryDoorknob() {
console.log("You clicked the doorknob")
if (hasBluekey == true) {
doorknob = "unlocked";
alert("The doorknob is now unlocked");
checkRoom();
} else {
alert("You need a key");
}
}
function tryComboLock() {
console.log("You clicked the combo lock");
var comboTry = prompt("You enter the combination...");
if (comboTry == "AV70") {
comboLock = "unlocked";
alert("The combination was correct");
checkRoom();
} else {
alert("The combination was incorrect");
}
}
function grabBluekey() {
console.log("You clicked the blue key");
hasBluekey = true;
alert("You picked up the key");
document.getElementById("bluekey").style.display = "none";
}
function checkRoom() {
if (doorknob == "unlocked") {
if (comboLock == "unlocked") {
document.getElementById("next").style.visibility = "visible";
} else {
alert("You push on the door but still need a combination");
}
} else {
alert("You try to turn the door knob but is still locked");
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="room">
<img id="door" src="door1.png" onclick="tryDoor()">
<img id="doorknob" src="doorknob1.png" onclick="tryDoorknob()">
<img id="comboLock" src="comboLock.png" onclick="tryComboLock()">
<img id="bluekey" src="blue_key.png" onclick="grabBluekey()">
<img id="clue" src="clue.png" onclick="lookClue()">
<img id="help" src="help.png" onclick="lookhelp()">
<img id="bloodMark" src="bloodMark.png">
<img id="table" src="table.png" onclick="moveTable()">
<img id="window" src="window.png">
<p id="thehelp"></p>
<p id="theclue">
</P>
<p id="thetable"></p>
</div>
<button id="next" onclick="window.location.href
='room2.html';">Proceed</button>
</body>
</html>
Your request seem impossible with an easy answer because you are displaying the text with console.log() I don't think it is possible to update individual lines of output in the console. It is not mentioned anywhere in the documentation. Your easy way out is to display the message or text in a separate element and update that element with the latest text as required. Here is how your code should look like now.
in your html add this code where you want the message to be displayed and style it however you want
<p id="text_message"></p>
And in your javascript code you should replace the console.log("your message"); to this text_message.innerHTML = "your message";
var hasBluekey = false;
var doorknob = "locked"
var comboLock = "locked"
function tryDoor() {
text_message.innerHTML = "You clicked the door";
}
function lookhelp() {
text_message.innerHTML = "You clicked on help";
let text = "Who needs help?";
document.getElementById("thehelp").innerHTML = text;
}
function lookClue() {
text_message.innerHTML = "You clicked on the clue";
let text = "Hmm, there are letters and numbers circled...";
document.getElementById("theclue").innerHTML = text;
}
function moveTable() {
text_message.innerHTML = "You clicked on the table";
let text = "You carefully move away the table with the broken vase";
document.getElementById("thetable").innerHTML = text;
document.getElementById("table").style.display = "none";
}
function tryDoorknob() {
text_message.innerHTML = "You clicked the doorknob";
if (hasBluekey == true) {
doorknob = "unlocked";
alert("The doorknob is now unlocked");
checkRoom();
} else {
alert("You need a key");
}
}
function tryComboLock() {
text_message.innerHTML = "You clicked the combo lock";
var comboTry = prompt("You enter the combination...");
if (comboTry == "AV70") {
comboLock = "unlocked";
alert("The combination was correct");
checkRoom();
} else {
alert("The combination was incorrect");
}
}
function grabBluekey() {
text_message.innerHTML = "You clicked the blue key";
hasBluekey = true;
alert("You picked up the key");
document.getElementById("bluekey").style.display = "none";
}
function checkRoom() {
if (doorknob == "unlocked") {
if (comboLock == "unlocked") {
document.getElementById("next").style.visibility = "visible";
} else {
alert("You push on the door but still need a combination");
}
} else {
alert("You try to turn the door knob but is still locked");
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p id="text_message" style="background-color:grey;color:white;"></p>
<div id="room">
<img id="door" src="door1.png" onclick="tryDoor()">
<img id="doorknob" src="doorknob1.png" onclick="tryDoorknob()">
<img id="comboLock" src="comboLock.png" onclick="tryComboLock()">
<img id="bluekey" src="blue_key.png" onclick="grabBluekey()">
<img id="clue" src="clue.png" onclick="lookClue()">
<img id="help" src="help.png" onclick="lookhelp()">
<img id="bloodMark" src="bloodMark.png">
<img id="table" src="table.png" onclick="moveTable()">
<img id="window" src="window.png">
<p id="thehelp"></p>
<p id="theclue">
</P>
<p id="thetable"></p>
</div>
<button id="next" onclick="window.location.href
='room2.html';">Proceed</button>
</body>
</html>
You could try to use ANSI escape codes -- they are really useful for formatting text in a terminal after it's been printed. For this you would want to use cursor controls and erase functions. these are from this tutorial, which was very helpful for a project I made a while ago. Not all of them work on every platform (e.g. replit, not sure if anyone actually uses that though) but overall it's a good system.
example:
console.log("normal text");
//bold, red foreground
console.log("\u001B[1;31m");
console.log("edited text");
(example from the tutorial)
I'm bad at making examples, but I found the two aforementioned sections to be good for quick reference. To truly comprehend how to use it, I suggest that you read through the whole thing.

Why is if...else statement only compares single word values?

I am making a quiz app that will basically fetch the questions and answers from an API and display it to the webpage. It works fine, but the error handling isn't working. I have a if...else statement that will check if a user has selected the right answer, and if they did, play a sound and display "Nice job" to the user. If they did not, then tell the user that they need to try again. The behavior that I'm getting is very weird. Sometimes when I have chose the correct answer, it says it is not correct. It happens when there is spaces within the answer. For single words such as "true", "false" or "Hello" works fine. I logged the answer to the console stored in a variable called answer_container, when I logged it to the console, the answer and my choice are exactly the same. I have tried using === and == operators to see if that would work, but the result is the same. I have posted the full code including my HTML so that you can see what it is happening. Note it took me couple of tries to get the weird behavior to display.
Here is what I have tried:
var showAnswer = document.getElementById('showAnswer');
var button_score = document.getElementById('ShowScore');
var answer_container;
var url = 'https://opentdb.com/api.php?amount=1';
var score = 0;
var html_container = [];
async function fetchData() {
document.getElementById('next').disabled = true;
document.getElementById('msgSuccess').innerHTML = '';
document.getElementById('check').disabled = false;
document.getElementById('showAnswer').disabled = false;
var getData = await fetch(url);
var toJS = await getData.json();
answer_container = toJS.results[0].correct_answer;
var container = [];
for (var i = 0; i < toJS.results[0].incorrect_answers.length; i++) {
container.push(toJS.results[0].incorrect_answers[i]);
}
container.push(toJS.results[0].correct_answer);
container.sort(func);
function func(a, b) {
return 0.5 - Math.random();
}
html_container = [];
container.forEach(function(choices) {
html_container.push(`
<option value=${choices}>
${choices}
</option>
`)
});
document.getElementById('choice').innerHTML = html_container.join();
if (toJS.results[0].type === 'boolean') {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a true/false question<br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
} else {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a ${toJS.results[0].type} choice question <br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
}
}
fetchData();
showAnswer.addEventListener('click', function() {
document.getElementById('answer_element').innerHTML = "The answer to this question is " + answer_container;
document.getElementById('answer_element').style.display = "block";
setTimeout(function() {
document.getElementById('answer_element').style.display = "none";
}, 3000);
});
function check() {
var select_answer = document.getElementById('choice').value;
var audio = document.getElementById('audio');
if (select_answer == answer_container) {
score++;
document.getElementById('showAnswer').disabled = true;
document.getElementById('msgSuccess').innerHTML = "Nice job, keep going!";
document.getElementById('next').disabled = false;
document.getElementById('check').disabled = true;
audio.play();
console.log(answer_container);
}
if (select_answer != answer_container) {
score--;
document.getElementById('msgSuccess').innerHTML = "Keep trying, you will get it!";
document.getElementById('next').disabled = true;
console.log(answer_container);
}
}
<!DOCTYPE html>
<html>
<head>
<title>
Quiz App
</title>
</head>
<body>
<div id="type">
</div>
<label>
Select Your Answer...
</label>
<select id="choice">
</select>
<button id="showAnswer">
Show Answer
</button>
<p id="answer_element">
</p>
<button onclick="check()" id="check">
Check
</button>
<p id="msgSuccess">
</p>
<button id="next" onclick="fetchData()">
Next Question
</button>
<audio id="audio">
<source src="https://www.theharnishes.com/khanacademy.mp3" type="audio/mp3">
</audio>
</body>
</html>
You're using the expression select_answer == answer_container to determine if the choice is the correct answer.
select_answer comes from the value attribute of the option you've selected. However, when an answer value contains whitespace, HTML interprets only up to the first whitespace as the "value". When answers like North America come up, the option's value attribute is only North.
When generating your options in your HTML, you need to properly encapsulate them in double quotes ", like so:
html_container.push(`
<option value="${choices}">
${choices}
</option>
`)
Tangential, but it would probably be cleaner if you generated your elements with document.createElement() and Node.appendChild(); in this instance the quotes required to properly set the value attribute on each option would have been added for you.
Nice game!
The issue here is the text is getting truncated on whitespace in the HTML, so the value you're comparing it too doesn't match.
You need quotes in the HTML option to preserve white space.
<option value=${choices} <- picks the first word
<option value="${choices}" <- allows the whole string with spaces
var showAnswer = document.getElementById('showAnswer');
var button_score = document.getElementById('ShowScore');
var answer_container;
var url = 'https://opentdb.com/api.php?amount=1';
var score = 0;
var html_container = [];
async function fetchData() {
document.getElementById('next').disabled = true;
document.getElementById('msgSuccess').innerHTML = '';
document.getElementById('check').disabled = false;
document.getElementById('showAnswer').disabled = false;
var getData = await fetch(url);
var toJS = await getData.json();
console.log(toJS)
answer_container = toJS.results[0].correct_answer;
var container = [];
for (var i = 0; i < toJS.results[0].incorrect_answers.length; i++) {
container.push(toJS.results[0].incorrect_answers[i]);
}
container.push(toJS.results[0].correct_answer);
container.sort(func);
function func(a, b) {
return 0.5 - Math.random();
}
html_container = [];
container.forEach(function (choices) {
html_container.push(`
<option value="${choices}">
${choices}
</option>
`)
});
document.getElementById('choice').innerHTML = html_container.join();
if (toJS.results[0].type === 'boolean') {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a true/false question<br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
}
else {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a ${toJS.results[0].type} choice question <br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
}
}
fetchData();
showAnswer.addEventListener('click', function () {
document.getElementById('answer_element').innerHTML = "The answer to this question is " + answer_container;
document.getElementById('answer_element').style.display = "block";
setTimeout(function () {
document.getElementById('answer_element').style.display = "none";
}, 3000);
});
function check() {
var select_answer = document.getElementById('choice').value;
var audio = document.getElementById('audio');
console.log(select_answer, answer_container)
if (select_answer == answer_container) {
score++;
document.getElementById('showAnswer').disabled = true;
document.getElementById('msgSuccess').innerHTML = "Nice job, keep going!";
document.getElementById('next').disabled = false;
document.getElementById('check').disabled = true;
audio.play();
console.log(answer_container);
}
if (select_answer != answer_container) {
score--;
document.getElementById('msgSuccess').innerHTML = "Keep trying, you will get it!";
document.getElementById('next').disabled = true;
console.log(answer_container);
}
}
<!DOCTYPE html>
<html>
<head>
<title>
Quiz App
</title>
</head>
<body>
<div id="type">
</div>
<label>
Select Your Answer...
</label>
<select id="choice">
</select>
<button id="showAnswer">
Show Answer
</button>
<p id="answer_element">
</p>
<button onclick="check()" id="check">
Check
</button>
<p id="msgSuccess">
</p>
<button id="next" onclick="fetchData()">
Next Question
</button>
<audio id="audio">
<source src="https://www.theharnishes.com/khanacademy.mp3" type="audio/mp3">
</audio>
</body>
</html>

setting variable value on click

Im new in programming and im trying to make my first project in js - hangman game (https://en.wikipedia.org/wiki/Hangman_(game))
So basically i got two buttons in my HTML file, lets say its look like this:
<button id="movies">Movies</button>
<button id="animals">Animals</button>
i want this buttons to be responsible for changing categories in my game. In js i got:
var movies = ["Shawshank Redemption","Alice in a Wonderland"];
var animals = ["Blue whale","Raspberry Crazy-Ant"];
var choice = 1;
if (choice === 0){
var pwdDraw = Math.floor(Math.random() * movies.length);
var pwd = movies[pwdDraw];
pwd = pwd.toUpperCase();
document.write(pwd);
}
else if (choice === 1){
var pwdDraw = Math.floor(Math.random() * animals.length);
var pwd = animals[pwdDraw];
pwd = pwd.toUpperCase();
document.write(pwd);
}
and this is the place where im stucked, i dont know how change var choice by clicking button (also i want to reload page after click). Im at the beginning on my way with js, so i want this code to be pure js, not any customized library.
<button onclick="changeCategory(number)">Click me</button>
<script>
function changeCategory() {
//[..]
}
</script>
https://www.w3schools.com/jsref/event_onclick.asp
thanks a lot for feedback, but i still have some troubles of implementing this js changes, When im doing it on new file with only category changer everything is running smooth. But when i try to add this to my existing code its doesnt work at all. Here you got my code:
codepen.io/iSanox/project/editor/DGpRrY/
First of all, don't put those <br> in JS code like that.
If you want to try to get the choice by clicking on the button then here's how you can do it:
HTML
<button id="movies" class="choice" value="0">Movies</button>
<br/>
<button id="animals" class="choice" value="1">Animals</button>
JS
var buttons = document.querySelectorAll(".choice");
function doSomething(e)
{
// You can get choice value by either doing:
var choice = e.target.value;
// OR
var choice = this.value;
// Continue your work here
}
for(var i = 0; i < buttons.length; i++)
{
buttons[i].addEventListener("click", doSomething);
}
Feel free to ask any questions.
Simply you can use onclick event. After some changes your code should look like this.
var movies = ["Shawshank Redemption", "Alice in a Wonderland"];
var animals = ["Blue whale", "Raspberry Crazy-Ant"];
var catname = document.getElementById('cat-name');
function selectCategory(choice) {
var pwd, pwdDraw;
if (choice === 0) {
pwdDraw = Math.floor(Math.random() * movies.length);
pwd = movies[pwdDraw];
} else if (choice === 1) {
pwdDraw = Math.floor(Math.random() * animals.length);
pwd = animals[pwdDraw];
}
pwd = pwd.toUpperCase();
catname.innerText = pwd;
}
<p>Choose Category</p>
<button id="movies" onclick="selectCategory(0)">Movies</button>
<button id="animals" onclick="selectCategory(1)">Animals</button>
<div id="cat-name"></div>
Even better with Object and Arrays
var categories = {
movies: ["Shawshank Redemption", "Alice in a Wonderland"],
animals: ["Blue whale", "Raspberry Crazy-Ant"]
};
var catname = document.getElementById('cat-name');
function selectCategory(choice) {
var pwdDraw = Math.floor(Math.random() * categories[choice].length);
var pwd = categories[choice][pwdDraw];
pwd = pwd.toUpperCase();
catname.innerText = pwd;
}
<p>Choose Category</p>
<button id="movies" onclick="selectCategory('movies')">Movies</button>
<button id="animals" onclick="selectCategory('animals')">Animals</button>
<div id="cat-name"></div>

localstorage how to save a button

I managed to save the text that is in the input field but the problem is that i do not know how to save the button. The buttons turn white when i click on them and the price of that seat will be visible in the input field. The price saves but the button does not stay white.
<script>
function changeBlue(element) {
var backgroundColor = element.style.background;
if (backgroundColor == "white") {
element.style.background = "blue";
add(-7.5)
} else {
element.style.background = "white";
add(7.5)
}
}
function add(val) {
var counter = document.getElementById('testInput').value;
var b = parseFloat(counter,10) + val;
if (b < 0) {
b = 0;
}
document.getElementById('testInput').value = b;
return b;
}
function save(){
var fieldValue = document.getElementById("testInput").value;
localStorage.setItem("text", fieldValue)
var buttonStorage = document.getElementsByClass("blauw").value;
localStorage.setItem("button", buttonStorage)
}
function load(){
var storedValue = localStorage.getItem("text");
if(storedValue){
document.getElementById("testInput").value = storedValue;
}
var storedButton = localStorage.getItem("button");
if(storedButton){
document.getElementsByClass("blauw").value = storedButton;
}
}
</script>
<body onload="load()">
<input type="text" id="testInput"/>
<input type="button" id="testButton" value="Save" onclick="save()"/>
<input class="blauw" type="button" id="testButton2" value="click me to turn white"
style="background-color:blue" onclick="changeBlue(this)">
<input class="blauw" type="button" id="testButton2" value="click me to turn white"style="background-color:blue" onclick="changeBlue(this)">
</body>
i made a small sample of what i want to do. And i do not want to use the Id's of the buttons because i have like 500 of them in a table.
That's because getElementsByClass (it's getElementsByClassName btw) returns a node list of all the elements with that class.
To make it work, you need to go through all the items in the list, using a for-loop, and set the value of each individual element to the localStorage-value.
See these links for more information:
Link 1
Link 2
Very small mockup to give you an idea:
(In the JS, I put in comments the lines of code you would be using for your situation.)
function changeValues() {
var list = document.getElementsByClassName("child"); //var list = document.getElementsByClassName("blauw");
for (var i=0; i<list.length; i++) {
list[i].innerHTML = "Milk"; //list[i].value = storedButton;
}
}
<ul class="example">
<li class="child">Coffee</li>
<li class="child">Tea</li>
</ul>
<p>Click the button to change the text of the first list item (index 0).</p>
<button onclick="changeValues()">Try it</button>

My localStorage.clear(); won't work

I am trying to make a simple program with localStorage. I created a button to reset all the data in the localStorage. Unfortunately, it won't work I don't know why.
Here's my code:
<script>
var slot = localStorage.getItem("slot");
if (slot == null) {
slot = 10;
}
document.getElementById("slot").innerText = slot;
function reduceSlot() {
if (slot >= 1) {
slot--;
document.getElementById("slot").innerText = slot;
localStorage.setItem("slot", slot);
}
else {
document.getElementById('slot').innerText = "FULL";
document.getElementById("button1").style.display = "none";
}
}
document.getElementById("button1").onclick = reduceSlot;
function clearLocalStorage(){
localStorage.clear();
}
</script>
<body>
<p id="slot">10</p>
Deduct
<button onclick="clearLocalStorage()">Clear All</button>
</body>
I followed this code in a website but it doesn't run. Most of the websites that I browsed were confusing. I need help.
<button onclick="window.localStorage.clear();">Clear All</button>
This should work.

Categories

Resources