I’m working on a stock market website called MyStok, and I’m trying to implement a search feature that listens for the Enter key press to trigger a search. However, the event listener is not firing, and nothing appears in the console when I press Enter or click the search button. I’m not sure why it isn’t working. Here’s my code:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MyStok</title>
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css"
integrity="sha512-Kc323vGBEqzTmouAECnVceyQqyqdsSiqLQISBL29aUW4U/M7pSPA/gEUZQqv1cwx4OnYxTxve5UMg5GT6L4JJg=="
crossorigin="anonymous" referrerpolicy="no-referrer"/>
</head>
<body>
<nav class="navbar">
<div class="navbar__container">
<a id="navbar__logo"><i class="fa-solid fa-chart-line"></i> MyStok </a>
<div class="navbar__toggle" id="mobile-menu">
<span class="bar"></span> <span class="bar"></span>
<span class="bar"></span>
</div>
<ul class="navbar__menu">
<li class="navbar__item"><a href="/MyStok/index.html" class="navbar__links">Home</a></li>
<li class="navbar__item"><a href="/MyStok/about.html" class="navbar__links">About Us</a></li>
<li class="navbar__item"><a href="/MyStok/analyse.html" class="navbar__links" id="analyseButton">Analyse</a></li>
<li class="navbar__button"><a href="/MyStok/signUp.html" class="button">Log In</a></li>
</ul>
</div>
</nav>
<div class="main">
<div class="main__container">
<div class="search-bar-container">
<a id="search-logo"><i class="fa-solid fa-chart-line"></i> MyStok </a>
<div class="search-bar">
<input type="search" id="search-input" placeholder="Search for a Stock Ticker...">
<button id="search-button"><i class="fa-solid fa-magnifying-glass"></i></button>
</div>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
JavaScript (app.js):
searchInput = document.getElementById("search-input");
searchInput.addEventListener("keypress", function(event) {
if (event.key === "Enter") {
console.log("Enter key pressed");
}
});
What I’ve Tried:
Added an eventListener to trigger on the keypress event for the Enter key.
Tried triggering the event listener with both the button and the Enter key.
Checked the console for errors, but there are no messages or errors showing up.
Expected Behaviour:
When the Enter key is pressed, a message should appear in the console saying “Enter key pressed.”
Problem:
The keypress event is not triggering, and I’m not sure why. Is there something wrong with how I set up the event listener?