I’m creating a mock website using html, Javascript and CSS. I want to move from one page to another (home.html to TVShows.html) by pressing on the list “TV Shows” on navigation bar. Usually i’d just assign href but i want to code this interaction using Javascript instead. Here’s my attempt but it doesn’t work.
Html:
<li><a id="TVShows" href="#">TV
Shows</a></li>
Javascript:
// Function to handle navigation to TV Shows page
document.getElementById('TVShows').addEventListener('click', function(event) {
event.preventDefault(); // prevent default link behavior
console.log("TV Shows link clicked");
// Redirect to TV Shows page
window.location.href = 'TVShows.html';
});
I’ve tried different methods of writing this none have worked.
3
Answers
I found the issue. I was using one javascript file for all the pages and calling the same .js src on each html file. Seems like you need separate .js files for each html or write the script directly in the html.
This standalone page works. So the error is elsewhere, in some other code you’ve not shown us.
make sure that your script is at the end of your html file, otherwise the element might not exist yet (because not loaded) or you can also use this: