I am a JavaScript beginner and when I was making a HTML, CSS, JS project with VSCode, I encountered the following error:
Uncaught TypeError: Cannot read properties of null (reading at 'addEventListener')
Also, My project was: Make a login + register system with just JavaScript dictionaries, and a logged_in variable (that will redirect people to the registration page if it's false)
HTML Registration file:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>BeedHub Register</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='style.css'>
<script src='index.js'></script>
</head>
<body>
<h1 class="hello_world">Welcome!</h1>
<p class="aaa">We're so excited to see you!</p>
<div class="usernamediv">
<input id="main_usr" placeholder="Write username here" type="text">
</div>
<div class="passworddiv">
<input id="main_pw" placeholder="Write password here" type="password">
</div>
<div class="btn">
<button id="main_register">Register!</button>
</div>
<div class="login_instead">
<a href="C:\Users\directory\.vscode\directory\directory\directory\login">Login Instead</a>
</div>
</body>
</html>
JavaScript file:
// Variables
var db = {
};
var logged_in = false;
// Register Elements
var rg_usr = document.getElementById("main_usr");
var rg_pw = document.getElementById("main_pw");
var rg_submit = document.getElementById("main_register");
// Event Listeners
rg_submit.addEventListener('click',function() {
if (db[rg_usr.innerHTML]) {
var error_usr_taken = document.createElement("p");
error_usr_taken.innerHTML = "Error: Username Already Taken!";
} else if (rg_usr.innerHTML == "" || null) {
var error_usr_none = document.createElement("p");
error_usr_none.innerHTML = "Error: Username is null!";
} else if (rg_pw.innerHTML == "" || null) {
var error_pw_none = document.createElement("p");
error_pw_none.innerHTML = "Error: Password is null!";
} else {
db[rg_usr.innerHTML] = rg_pw.innerHTML;
logged_in = true;
window.location.pathname = "/successpage";
};
});
If you want me to provide more information, comment with a ping.
P.S. I have also used the script tag on my /login/index.html file, but the web says that multiple HTML files using the same JavaScript file have no problem.
Thanks in advance,
Beedful
` tag so the document can load. There are other ways to approach this but this is the quickest.
– Andy Jan 15 '22 at 11:41