I am currently developing a "Gamebook Engine" that enables users to set a custom username. The user name is extracted from an input element with the id="setUserNameInput" and stored using the function setUserName(). It is then displayed or loaded into an element with the class="displayUserName" through the function displayUserName(). Everything works smoothly when there is only one class on the page, but when additional classes are added, I have to specify which one to target as it does not automatically target all of them. I have experimented with document.getElementById, document.getElementsByName, document.querySelectorAll, and document.querySelector without success. (Just a side note, I am utilizing Bulma as my CSS Framework)
Here is the code snippet I have constructed so far (note: accessing localStorage will result in an error in this snippet): You can find an operational example on this page . Since this is a documentation page hosted on my testing server, you may also want to refer to for details regarding individual elements (please note that the documentation is in German, but I can provide a translation if needed).
The specific section of JavaScript that I am struggling with is mentioned right at the beginning, however, any general improvements or suggestions would be greatly appreciated.
var userNameOutput = document.getElementsByClassName('displayUserName')[0];
function setUserName() {
var usernameinput = document.getElementById('setUserNameInput').value;
localStorage.setItem('userName', usernameinput);
if (!localStorage.getItem('userName')) {
setUserName();
} else {
var storedUserName = localStorage.getItem('userName');
userNameOutput.innerHTML = storedUserName;
}
}
function displayUserName() {
if (!localStorage.getItem('userName')) {
setUserName();
} else {
var storedUserName = localStorage.getItem('userName');
userNameOutput.innerHTML = storedUserName;
}
}
window.onload = function displayUserName() {
if (!localStorage.getItem('userName')) {
setUserName();
} else {
var storedUserName = localStorage.getItem('userName');
userNameOutput.innerHTML = storedUserName;
}
}
<input type="text" class="input" placeholder="Your name goes here" id="setUserNameInput">
<input type="button" class="button" value="Set your username" onclick="setUserName()" />
<input type="button" class="button" value="Display on click" onclick="displayUserName()" />
<br> So you shall be called <span class="displayUserName"></span>! But dont worry, <span class="displayUserName"></span>, it will be all fine.