I'm trying to make a quiz web app with javascript and I am stuck. There are 2 HTML files, one as starter.html and one as index.html. I have an input in my starter file which takes in a username which I want to display later on the index site like:
alert(`Congrats ${playerName} you got all the questions right!`)
and a "submit" link which takes you to the next site and stores a variable like this:
<input type="text" id="username" placeholder="Enter your name"/>
<a id="startGame" href="index.html">Start Game</a>
const inputArea = document.querySelector("#username");
const startButton = document.querySelector("#startGame");
var saveUsername = function () {
var playerName = inputArea.value;
};
How can i access the playerName variable from the index.html? Firstly, I intended to use a global js file but I miss some declared elements since i have two separate html file and it does not find the elements during the DOM manipulation (cannot read properties of null). I tried using two separate js file but I couldn't find the solution to access data from a javascript file and store it in the second one.
Any ideas?
You can use localStorage
for that purpose. When a user enters his / her name in the textbox you can save the value to localStorgae
and fetch the value on the index page.
const usernameInputField = document.querySelector('#username'),
button = document.querySelector('button');
button.addEventListener('click', () => {
if (usernameInputField.value != "") {
localStorage.setItem('user', usernameInputField.value);
}
alert('Username Saved Successfully. Starting the game...');
})
<input type="text" id="username" placeholder="Enter your name" />
<button>Start Game</button>
and to get the value back, simply use
if(localStorage.getItem != null && localStorage.getItem('user') != "") {
console.log(localStorage.getItem('user'));
// here you can set the name as innerText of some element
}
You can check this out here https://jsfiddle.net/za01kp46/