I have decided to work with Firebase instead of using SQL and PHP, which is making the backend development easier. However, I'm getting the
TypeError: Cannot read property 'style' of null error for the ID element: login_div.
Most of this code is from a YouTube video Firebase web login tutorial. The issue started when I attempted to move the log out button out of the index page and onto another HTML file. I decided to keep a copy on both, however, the whole page keeps constantly refreshing and going back and forth between login page and my homepage, if the line document.getElementById("login_div").style.display = "block";
is changed or removed and I don't know how to fix this. I tried changing the ID name which did nothing and tried moving the div into the homepage which just started refreshing the whole page over and over again.
firebase.auth().onAuthStateChanged(function(user) {
//checking with firebase if there is a user
if (user) {
// User is signed in successful
//document.getElementById("user_div").style.display = "block";
document.getElementById("login_div").style.display = "none";
var user = firebase.auth().currentUser;
if (user !== null) {
//what to display if user is logged in
window.location.href = "chat.html";
}
} else {
// No user logged in displays login div hides user div
document.getElementById("user_div").style.display = "none";
document.getElementById("login_div").style.display = "block";
}
});
function login() {
var userEmail = document.getElementById("email_field").value;
var userPassword = document.getElementById("password_field").value;
firebase.auth().signInWithEmailAndPassword(userEmail, userPassword).catch(function(error) {
// Error messages for failed login
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error: " + errorMessage);
});
}
function logout() {
//log out function
firebase.auth().signOut().then(function() {
window.location.href = "index.html";
});
}
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<!-- login in page and button -->
<div id="login_div" class="main-div">
<h1>The Bridge Login</h1>
<input type="email" placeholder="Email..." id="email_field" />
<input type="password" placeholder="Password" id="password_field" />
<button onclick="login()">Log In</button>
</div>
<div id="user_div" class="loggedIn-div">
<button onclick="logout()">Logout</button>
</div>
<!-- firebase authentication server connection-->
<script src="https://www.gstatic.com/firebasejs/4.10.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
</script>
<script src="index.js"></script>
</body>
</html>