Search code examples
javascripthtmljqueryhrefnavigationbar

Having navigation bar href path routing issues whenever I am in a new html page


When I first load the page to index.html everything loads fine. I press the About link in the navigation bar to direct to the about.html page and it loads fine. But when I press on the About link again while I am in the about.html page it throws of an error that it cannot find it. I am guessing the href file paths change when routing to a different html page. I am not sure how to fix this issue. Also I am using a customized navigation-bar tag so I have one place to reference it as a component and reuse it in every page. This logic is in the main.js file.

//This is the main.js file
class Navigation extends HTMLElement {
    connectedCallback(){
        this.innerHTML = `
    <div class="menuContainer fadeInDown-animation">
        <div class="item"><a href="index.html"><button class="btn">Home</button></a></div>
        <div class="item"><a href="htmlPages/about.html"><button class="btn">About</button></a></div>
        <div class="item"><button class="btn">Skills</button></div>
        <div class="item"><a href="contact.html"><button class="btn">Contact</button></a></div>
    </div> 
    `
    }
}

customElements.define('navigation-bar', Navigation);

Here is my file structure:
src/index.html
src/htmlPages/about.html
src/htmlPages/contact.html
src/javascript/main.js
src/jquery-3.7.1.min.js
src/css/style.css


Solution

  • your issue is happening because of the way your links are set up. When you're on index.html, clicking "About" works fine, but when you're already on about.html, the browser looks for htmlPages/htmlPages/about.html, which doesn’t exist.

    Fix Relative Path: Change your link to:

    <a href="./about.html">About</a>
    

    Fix Absolute Path: Use this instead:

    <a href="/src/htmlPages/about.html">About</a>
    

    Fix JavaScript Fix for Components

    class Navigation extends HTMLElement {
        connectedCallback() {
            const basePath = window.location.pathname.includes("/htmlPages/") ? "../" : "";
            this.innerHTML = `
                <a href="${basePath}index.html">Home</a>
                <a href="${basePath}htmlPages/about.html">About</a>
                <a href="${basePath}htmlPages/contact.html">Contact</a>
            `;
        }
    }
    customElements.define('navigation-bar', Navigation);