Search code examples
htmlanchorhref

Link with anchor to different page (href)


I have a page with working anchors like these:

<a class="nav-link" href="#ta-services">Leistungen</a>
...
<section class="border-top" id="ta-services">

On another page, I want to link to the first page at the same anchors position. In my understanding, that should be possible with plain html:

<a class="nav-link" href="index.html#ta-services">Leistungen</a>

However, the link works just like a normal link to index.html, the page does not scroll down. Example online at http://elisabethzenz.at/impressum_datenschutz.html. Link in the upper right named "Leistungen".

The website is based on a bootstrap template, it might be some interference with the full screen header image – I would appreciate any hints how to solve the issue!


Solution

  • The native navigation to fragment works correctly. You have some JavaScript that scrolls the page to top when the URL has a hash component.

    In assets/js/theme.js around line 702:

      var hash = window.location.hash;
    
      if (hash && document.getElementById(hash.slice(1))) {
        var $this = $(hash);
        $('html, body').animate({
          scrollTop: $this.offset().top - $("a[href='" + hash + "']").data('offset')
        }, 400, 'swing', function () {
          window.history.pushState ? window.history.pushState(null, null, hash) : window.location.hash = hash;
        });
      }
    

    $("a[href='" + hash + "']").data('offset') returns undefined, so scrollTop: NaN = scrollTop: 0

    You could just remove all that code, and it will work.

    Or make sure that operation doesn't return NaN:

    scrollTop: $this.offset().top - ($("a[href='" + hash + "']").data('offset') || 0)