I'm learning HTML and I'm trying to do some very basic stuffs. I have my main page under index.html, a registration form under registration.html, and a script under script.js.
Index.html has the following button: <BUTTON id="login" onclick="register()">login/registration</BUTTON>
function register()
{
if (!loggedIn)
document.location.href = "registration.html";
else
{
// Page not created yet
//document.location.href = "aacount.html";
console.log("redirecting to account page");
}
In script.js, at the top, I have let loggedIn = false;.
The form's submission button looks like this: <button type="submit" class="submit" onclick="submit()"><b>Submit</b></button>
function submit(){loggedIn = true;}
Now on my main page, I have the login button. I would like it to change to an Account button so I made this:
function checkLog()
{
if (loggedIn == true)
document.getElementById("login").textContent = "Account";
else
document.getElementById("login").textContent = "Login/Registration";
}
I want my form, which has the header form class="registration_form" action="index.html" method="post" id="form" to redirect to the main page once you click submit. Since you're now logged in, I want the login/registration to swap to an account button. I don't have any backend because I haven't learned how yet. I just want to modify index.html once it loads back in by using the checkLog() function. Is there a way to do this using only HTML/JavaScript? I have seen a couple solutions using PHP, but I will only jump into it next week once I have more free time. Until then, can I make it work this way?
Just to be sure, I have tried adding onload="checkLog()" to both the entire body text and the login button to no avail. I've also found out that adding onclick="checkLog()" on the submit button in the form doesn't do anything since it executes before the action of changing web pages occur. I basically want a onclick="" that occurs after the action.
As a lot suggested in the comments, since there is no server-side to your project yet you're trying to check if the user is logged in to your website, your best bet is either cookies or LocalStorage. In this answer I will take the LocalStorage approach.
function register()
{
if (localStorage.getItem("userAuthentication") === null)
storage.setItem("userAuthentication", "userAuthentication");
document.getElementById("login").textContent = "Login/Registration";
else {
// User is logged in
// Since the user must have localStorage set up
console.log("redirecting to account page");
document.getElementById("login").textContent = "Account";
}
}
The getItem attribute returns null if the item does not exist; meaning the item hasn't been set yet. if so, we need to set LocalStorage, and change the login button text to "Login/Registration". Else, the localStorage has to be set, meaning we can can change the login button text to "Account".