js: Show text saved in localStorage on same page - javascript

I'm a total beginner in javascript and spend too much time trying to get this working.
What I want to do:
1.html generates sentences from different arrays. So the user can push the button "generate" and the arrays will combine randomly, as long as there is a sentence he/she likes. I need this generated sentence on 2.html. I used localStorage to store the generated sentence. The thing I want to get working is, that the generated sentence on 1.html is also shown on 1.html after the User pushes the "generate" button. Never got it working properly.
I replaced the words of the sentences with letters for now.
Here the code of 1.html
let green, display, button, clock, end;
green = ["a", "d", "d", "v"];
display = ["f", "g", "v", "h"];
button = ["h", "r", "h", "h"];
clock = ["h", "t", "c", "r"];
end = ["g", "t", "x", "r"];
function sentence() {
let rand1 = Math.floor(Math.random() * 4);
let content = clock[rand1] + " " + display[rand1] + " " + button[rand1] + " " + green[rand1] + " " + end[rand1];
return content;
}
// Check browser support
if (typeof(Storage) !== "undefined") {
localStorage.setItem("sentence", sentence());
}
<h1>Generator</h1>
<button onclick="sentence()">generate</button>
This is 2.html
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
document.getElementById("result").innerHTML = localStorage.getItem("sentence");
} else {
document.getElementById("result").innerHTML = "Browser does not support Web Storage.";
}
</script>

The function sentence() does not by itself save to localStorage. It only generates a new sentence each time it's called. You can change as follows:
function sentence() {
let rand1 = Math.floor(Math.random() * 4);
let content = clock[rand1] + " " + display[rand1] + " " + button[rand1] + " " + green[rand1] + " " + end[rand1];
// Check browser support
if (typeof(Storage) !== "undefined") {
localStorage.setItem("sentence", content);
}
const message = document.querySelector('.message');
message.innerText = content;
}
And in 1.html add this:
<div class="message"></div>

Related

js: hand generated text to next site

i use this js code to generate text:
let green, display, button, clock, end;
green = ["x", "t", "g", "l"];
display = ["l", "h", "r", "e"];
button = ["e", "D", "l", "w"];
clock = ["o", "b", "a.", "e"];
end = ["T", "g", "t", "w"];
function randGen() {
return Math.floor(Math.random() * 4);
}
function sentence() {
let rand1 = Math.floor(Math.random() * 4);
let content = clock[rand1] + " " + display[rand1] + " " + button[rand1] + " " + green[rand1] + " " + end[rand1];
document.getElementById('sentence').innerHTML = """ + content + """;
};
sentence();
and put it in html like this:
<button style="" onclick="sentence()">generate text<i class="fa fa-refresh" aria-hidden="true"></i></button>
<div class="container">
<p id="sentence"></p>
</div>
Now i want to use the generated text the user generates by hitting the "generate text"-button on another html-document. Is it possible? Do i need to safe this text anywhere before using it on another html-document?
thanks in advance
John
You can use localStorage to solve your problem.
Save your sentence to localStorage like this:
function sentence() {
let rand1 = Math.floor(Math.random() * 4);
let content = clock[rand1] + " " + display[rand1] + " " + button[rand1] + " " + green[rand1] + " " + end[rand1];
return content;
};
// Check browser support
if (typeof(Storage) !== "undefined") {
localStorage.setItem("sentence", sentence());
}
And get sentence value on another page like this:
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
document.getElementById("result").innerHTML = localStorage.getItem("sentence");
} else {
document.getElementById("result").innerHTML = "Browser does not support Web Storage.";
}
</script>
Hopefully, it will help your problem. Please let me know if you have any issues.

Changing object value with onClick event

Sorry to ask this again, but I wanted to add more code for context.
I am making a rock paper scissors game and want to change the playerChoice key when a button the button is pressed.
I want to add an onclick event to each button and run a function that will set the playerChoice property so it references the gameOptions index.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Lapis, Papyrus Scalpellus</h1>
<h2>Make a Choice</h2>
<button id="Lapis">Lapis</button>
<button id="Papyrus">Papyrus</button>
<button id=Scalpellus>Scalpellus</button>
<h2>Game Results</h2>
<script src="script.js"></script>
</body>
</html>
const gameOptions = ["Lapis", "Papyrus", "Scalpellus"];
const newChoice = randomChoice();
console.log(newChoice);
const humanPlayer = {
playerChoice: gameOptions[0],
};
const computerPlayer = {
playerChoice: randomChoice(),
};
document.querySelector("#Lapis").onclick = function() {
humanPlayer.playerChoice = gameOptions[0];
};
document.querySelector("#Papyrus").onclick = function() {
humanPlayer.playerChoice = gameOptions[1];
};
document.querySelector("#Scalpellus").onclick = function() {
humanPlayer.playerChoice = gameOptions[2];
};
console.log(humanPlayer);
//Random Choice
function randomChoice() {
const theChoice = gameOptions[Math.floor(Math.random() * 3)];
return theChoice;
}
//Players
function resultText(innerText){
const paragraph = document.createElement('p');
paragraph.innerText = innerText;
document.body.appendChild(paragraph);
}
//Outcomes
function fight(){
if(computerPlayer.playerChoice === humanPlayer.playerChoice){
resultText("Its a Tie!20. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}else if (computerPlayer.playerChoice === "Lapis"){
if(humanPlayer.playerChoice === "Papyrus"){
resultText("Human Player Wins!6. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}else if( humanPlayer.playerChoice === "Scalpellus"){
resultText("Computer Player Wins!5 You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}
}else if(computerPlayer.playerChoice === "Papyrus"){
if ( humanPlayer.playerChoice === "Lapis"){
resultText("Compter Player Wins!4. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}else if( humanPlayer.playerChoice === "Scalpellus"){
resultText("Human Player Wins!3. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}
}else if(computerPlayer.playerChoice === "Scalpellus"){
if ( humanPlayer.playerChoice === "Lapis"){
resultText("Human Player Wins!2. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}else if( humanPlayer.playerChoice === "Papyrus"){
resultText("Computer Player Wins!1. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}
}
}
fight()
You can use the following to keep your code simple:
var btns = document.querySelectorAll("button");
for (var i = 0; i < btns.length; i++){
btns[i].addEventListener("click", btnHandler);
}
And then your handler function will be called each time a button is clicked without the need to repeat your code:
function btnHandler(el){
switch (el.getAttribute("id")){
case "Papyrus":
...
default: break;
}
}
It also allows you to pass the button element itself, so you can just pull out the ID attribute when needed, rather than having to pass a parameter for each different instance across separate calls. For the win condition check, you can eliminate several "if" statements by simply seeing if they're equal, and if they're not, only compare the human choice to the computer choice which would beat it and set the result thusly. It can be optimized further, but I imagine you would like to learn something from this so I've commented the fiddle as well.
For this example, I also moved the fight() function to the button handler so the player would have a choice, and the computer's choice would only be triggered at that point as well. There were a few instances in your original code which called functions and set variables, but didn't use them etc, as well as a few syntax errors.
See attached fiddle:
https://jsfiddle.net/s0toz3L8/2/

reset var to blank after running loop in javascript

HELP! I have been banging my head against the wall for hours and hour trying to find a way that once my "game" has ended either by winning or losing my lettersGuessed var resets and no longer displays my userGuesses. I can get through the first loop/ round by setting lettersGuessed = ""; but when a new userGuess is entered, I get an uncaught type error that lettersGuessed is not a function.
// array of letters for the computer to chose from
var letterBank = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
var lettersGuessed = []
// variables starting value for tally counter
var wins = 0;
var losses = 0;
var guessesLeft = 6;
var compGuess = letterBank[Math.floor(Math.random() * letterBank.length)];
for (var i = 0; i <= guessesLeft; i++) {
document.onkeyup = function(event) {
// var for use of collecting key answers for both user and computer.
var userGuess = event.key;
lettersGuessed.push(userGuess);
// if statements to get a win or loss
if (userGuess === compGuess) {
guessesLeft = 7;
alert("You won!")
compGuess = letterBank[Math.floor(Math.random() * letterBank.length)];
userGuess = "";
lettersGuessed = "";
wins++;
}
if (userGuess != compGuess) {
guessesLeft--;
}
if (guessesLeft === 0) {
alert("GAME OVER");
guessesLeft = 6;
losses++;
userGuess = "";
compGuess = letterBank[Math.floor(Math.random() * letterBank.length)];
}
// variables to display a win/loss tally and the computer/user guesses
var html =
"<p> your choice: " + userGuess + "</p>" +
"<p> losses: " + losses + "</p>" +
"<p> wins: " + wins + "</p>" +
"<p> Guesses left: " + guessesLeft + "</p>" +
"<p> Your Guesses so far:" + lettersGuessed + "</p>";
// sends info collected from html var to the game div
document.querySelector("#game").innerHTML = html;
};
};
<div id="game">Type a letter</div>
lettersGuessed is an array when declared and not a string. To reset, you need to use the same code as the first initialization. So in your first if statement, replace
lettersGuessed = "";
with
lettersGuessed = [];

I'm trying to clear the input field after the button is clicked

I need the input field to clear after the user clicks the button to convert the number they've entered. I'm having a difficult time figuring this out, if anyone can help i feel like it's a very simple solution but, I can't seem to wrap my head around it.
(function () {
//Constants
const KM_TO_MILES = 0.625;
const MILES_TO_KM = 1.6;
var user = prompt("So..What's your name beautiful?");
if (user === null) {
alert("NOOOOO, you cancel me? meanie.")
remove();
}
//on load function
window.onload = function () {
var result = document.getElementById("result");
//display the user's name with a message prompt to continue to enter a distance
result.innerHTML = "Okay, " + user + ", enter your distance and I will calculate for you, don't worry.";
document.getElementById("convertBtn").onclick = startConvert;
};
//on load function done
//conversion function
function startConvert() {
var placeholder = document.getElementById("distance").value;
var distanceInput = document.getElementById("distance").value;
var conversion = document.getElementById('List').value;
document.getElementById("List").value;
// If the user doesn't input a number run the alert
if ((placeholder === "") || (conversion == "Select Types")) {
alert("You didn't enter anything mate");
// If the user inputs a number and clicks KM to M then calculate it and in the html page change the text to show the answer.
} else if (conversion == "Kilometers to Miles") {
document.getElementById("result").innerHTML = "Okay, " + user + " ,the distance of " + distanceInput + " is equal to " + (distanceInput * KM_TO_MILES + " miles.");
// If the user inputs a number and clicks M to KM then calculate it and in the html page change the text to show the answer.
} else if (conversion == "Miles to Kilometeres") {
document.getElementById("result").innerHTML = "Okay, " + user + " ,the distance of " + distanceInput + " is equal to " + (distanceInput * MILES_TO_KM + " kilometers.");
}
}
//conversion function done
}());
document.getElementById('yourid').value = '';
you call this event on your button click surely it'll be works

"Document is missing (perhaps it was deleted?)" in reference to a document that was just created

My script creates a document, stores the document url in a cell on the spreadsheet, then another function opens said document using that url. I am getting the "Document is missing" error about 70% of the time I attempt to run it. Any ideas? the failure is on line 52.
function resultsDoc() {
var ssa = SpreadsheetApp;
var ss = ssa.getActiveSpreadsheet();
var sheets = ss.getSheets();
var ui = ssa.getUi();
var doca = DocumentApp;
var drive = DriveApp;
var template = "1uSCtqPwDYM-AtGAu3kzv3ZD0jdXnl12GxmdF_BDNb-M";
var source = doca.openById(template);
var resDocCopy = drive.getFileById(template).makeCopy('Tournament Results');
var resDocId = resDocCopy.getId();
var resDoc = doca.openById(resDocId);
var docBody = resDoc.getBody();
var resDocUrl = resDoc.getUrl();
sheets.shift();
for (var dis in sheets) {
var thisSheet = sheets[dis];
var letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "f"];
var disLetter = letters[dis];
var eventa = thisSheet.getName();
var aOne = thisSheet.getRange('B3').getValue() + " " + thisSheet.getRange('A3').getValue();
var aTwo = thisSheet.getRange('B4').getValue() + " " + thisSheet.getRange('A4').getValue();
var aThree = thisSheet.getRange('B5').getValue() + " " + thisSheet.getRange('A5').getValue();
var aFour = thisSheet.getRange('B6').getValue() + " " + thisSheet.getRange('A6').getValue();
var aFive = thisSheet.getRange('B7').getValue() + " " + thisSheet.getRange('A7').getValue();
var aSix = thisSheet.getRange('B8').getValue() + " " + thisSheet.getRange('A8').getValue();
docBody.replaceText('<<' + disLetter + '>>', eventa);
docBody.replaceText('<<' + disLetter + '1>>', aOne);
docBody.replaceText('<<' + disLetter + '2>>', aTwo);
docBody.replaceText('<<' + disLetter + '3>>', aThree);
docBody.replaceText('<<' + disLetter + '4>>', aFour);
docBody.replaceText('<<' + disLetter + '5>>', aFive);
docBody.replaceText('<<' + disLetter + '6>>', aSix);
}
ss.insertSheet("Links");
var linksSheet = ss.getSheetByName("Links");
linksSheet.getRange(1, 1).setValue("Link to results page:");
linksSheet.getRange(2, 1).setValue(resDocUrl);
Utilities.sleep(9000);
}
function sweepsDoc() {
var doca = DocumentApp;
var linksSheet = ss.getSheetByName("Links");
var resDocUrl = linksSheet.getRange(2, 1).getValue();
var resDoc = doca.openByUrl(resDocUrl);
var docBody = resDoc.getBody();
var sweepsSheet = ss.getSheetByName('Sweeps');
docBody.replaceText("<<sweeps1>>", sweepsSheet.getRange('B2').getValue());
docBody.replaceText("<<sweeps2>>", sweepsSheet.getRange('B3').getValue());
docBody.replaceText("<<sweeps3>>", sweepsSheet.getRange('B4').getValue());
}
Alright - so I figured out a "workaround" more than an actual solution. Instead of storing and accessing the document Url, I switched over to using the document's Id.
While I still don't understand why the Url causes it to lose track of the document, using the Id has 100% success rate over 20 attempts, while using the Url only had a 10% success rate over 20.
If you know what the problem with using the Url is, please let me know. If you're having the same problem, switch your code to use the doc id.
I'm not 100% sure, but I think not saving the document could be causing the problem.
Add the line below to the end of your code that builds the doc.
resDoc.saveAndClose();

Categories

Resources