Search code examples
htmlanchoranchor-scroll

Anchor tag doesn't work in second level pages


I've a menu that contains this content:

<div class="menu">
    <ol>
        <li data-target="home" ><a href="#home">hello</a></li>
        <li data-target="contact" ><a href="#contact">Contact</a></li>
        <li data-target="policy_privacy" ><a href="https://somesite.com/privacy_policy">Privacy</a></li>
    </ol>
</div>

when I'm in the home page the anchors working well (#home, #contact), but if I'm on privacy_policy page, and try to go to home page, nothing happen. How can I detect in some way if I'm not in home page (which contains the anchors) and redirect the user to the home?


Solution

  • If adding separate markup for the privacy_policy page in which you can add the link of the homepage in the anchor tag seems not easy then you should try something like this.

    if (window.location.href.includes("privacy_policy")) {
        document.querySelector('#home').href = "https://somesite.com";
    }