Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i get this javascript section to work

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading