I have a route "/login"
which has 2 input fields for email
and password
, and also there’s a button to click after filling up the fields, however, I have to add an event listener for the fields if there’s an Enter Keypress
because I want the user to send the data by pressing enter rather than mouse click manually on the button, and I don’t want to use forms
.
Now, when I add that event listener in the home page as shown below, it says element is null
since it cannot see it because it still didn’t load the content of "/login"
to the home page.
Any way to access those elements in different routes
?
Here’s the code for the index page "/"
:
<!DOCTYPE html>
<html>
<head>
<title>Vanilla SPA Router</title>
<meta charset="UTF-8" />
<link rel="stylesheet" href="css/styles.css" />
<link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet" />
</head>
<body>
<div id="root">
<nav id="main-nav" class="sidebar">
<a href="/" onclick="route()">Home</a>
<a href="/about" onclick="route()">About</a>
<a href="/lorem" onclick="route()">Lorem</a>
<a href="/login" onclick="route()">login</a>
</nav>
<div id="main-page"></div>
</div>
<script>
// adding event listener here for id elements password
var input = document.getElementById("password");
input.addEventListener("keypress", function(event) {
if (event.key === "Enter") {
event.preventDefault();
document.getElementById("login_btn").click();
}
});
// the login() will be called by login_btn, but I didn't include
// it for this question since it's unnecessary
</script>
<script src="router.js"></script>
</body>
The code for the login page "/login"
:
<input type="email" id="email" placeholder="email" />
<input type="password" placeholder="password" id="password" />
<button onClick="login()" id="login_btn" className="btn btn-primary">Login</button>
Javascript code for routing:
const route = (event) => {
event = event || window.event;
event.preventDefault();
window.history.pushState({}, "", event.target.href);
handleLocation();
};
const routes = {
404: "/pages/404.html",
"/": "/pages/index.html",
"/about": "/pages/about.html",
"/lorem": "/pages/lorem.html",
"/login": "/pages/login.html",
};
const handleLocation = async () => {
const path = window.location.pathname;
const route = routes[path] || routes[404];
const html = await fetch(route).then((data) => data.text());
document.getElementById("main-page").innerHTML = html;
};
window.onpopstate = handleLocation;
window.route = route;
handleLocation();