skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.


  2. <!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.

    Login or Signup to reply.
  3. 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:

    document.addEventListener('DOMContentLoaded', function() {
        var tvShowsLink = document.getElementById('TVShows');
        tvShowsLink.addEventListener('click', function(event) {
            event.preventDefault();
            console.log("TV Shows link clicked");
            window.location.href = 'TVShows.html';
        });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search