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.
>Solution :
<!doctype html>
<li><a id="TVShows" href="#">TV
Shows</a></li>
<script>
// 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';
});
</script>
This standalone page works. So the error is elsewhere, in some other code you’ve not shown us.