Search code examples
javascriptjqueryhtmlanchorsmooth-scrolling

Smooth Scroll blocks anchor link to other page


I am working on my portfolio website but I don't get the anchor links to work.

On the website you click on a case to view the details and after that I want to link back to the portfolio part of my website. I used anchor points to achieve this but my smooth scrolling is blocking the anchor links to another page. (I does work when I just link to the index but not when I add the anchor point & it also works when I remove the smooth scroll)

Does anyone know how I can fix this problem?

HTML:

<div class="menubalk" id="basic-menubalk">
 <!-- logo -->
 <a href="../index.html" class="logo-link">
  <div class="logo"></div>
 </a>
 <ul class="menu" id="basic-menu">
  <li><a href="../index.html#portfolio" id="margin-menu-rechts">Terug</a></li>
 </ul>
</div>  

Javascript:

$(document).ready(function(){
 "use strict";
 $("a").on('click',function(event) {
  if (this.hash !== "") {
   event.preventDefault();
   var hash = this.hash;    
   $('html, body').animate({
    scrollTop: $(hash).offset().top
   }, 800, function(){
    window.location.hash = hash;
   });
  } 
 });
}); 

Solution

  • The problem is the condition in your JavaScript code. if (this.hash !== "") { will evaluate to true for every link that contains a hash, not just the ones on your current page.

    Instead you could use:

    if (this.attributes.href.value.substr(0, 1) === '#') {
    

    Additionally, I would not use that jQuery script for smooth scrolling at all. There is a W3 standard that already works in some browsers (e.g. Firefox). And for the browsers that do not support it, you can use a polyfill (e.g. iamdustan/smoothscroll).