Search code examples
javascripthtmlformslocal-storageevent-listener

How to make username creation form stay invisible even on page reload?


So I'm a beginner in javascript, and I am coding a username creation form that displays the created username in a specified container. I already made the form and the EventListener that knows when I submit the form. The function that happens when the form is submitted, makes the form invisible and sets the item to localstorage. It also displays the created username in the container.(note: I know what i coded doesn't work in the code snippet, but I tested in in an actual html file and it works). I want to know, how to make the form invisible forever (even on page reload) if the username exists already, and how to make the username stay in the h1 container on page reload. All help is appreciated!

<!DOCTYPE html>
<html>

<body>
  <form id="username-creator" class="username-creator">
    <input type="text" id="username-creator-input" required>
    <button type="submit">Submit</button>
  </form>
  <div id="username-container">
    <h1 id="username-container-h1">
      <!-- This is where the created username goes -->
    </h1>
  </div>
  <script>
    document.getElementById('username-creator').addEventListener('submit', function(event) {
      event.preventDefault();
      var username = document.getElementById('username-creator-input').value;
      localStorage.setItem('username', username);
      document.getElementById('username-creator').style.display = "none";
      document.getElementById('username-container-h1').innerText = username;
    });
  </script>
</body>

</html>


Solution

  • You can modify your code to check for the existence of a stored username in localstorage and adjust the visibility of the form accordingly.

    Here's update code :

    <!DOCTYPE html>
    <html>
    
    <body>
      <form id="username-creator" class="username-creator">
        <input type="text" id="username-creator-input" required>
        <button type="submit">Submit</button>
      </form>
      <div id="username-container">
        <h1 id="username-container-h1">
          <!-- This is where the created username goes -->
        </h1>
      </div>
      <script>
       var storedUsername = localStorage.getItem('username');
       if (storedUsername) {
        document.getElementById('username-creator').style.display = "none";
        document.getElementById('username-container-h1').innerText = storedUsername;
                            }
        document.getElementById('username-creator').addEventListener('submit', function(event) {
          event.preventDefault();
          var username = document.getElementById('username-creator-input').value;
          localStorage.setItem('username', username);
          document.getElementById('username-creator').style.display = "none";
          document.getElementById('username-container-h1').innerText = username;
        });
      </script>
    </body>
    
    </html>