Search code examples
jquerybootstrap-4smooth-scrolling

How to avoid smooth scrolling on certain internal links?


I'm using the jQuery snippet from the most recent comment here. How can I avoid this behavior in the second case when a user clicks on a tab?

GOOD (it's working as it should):
<a href="#schedule">Schedule</a>

BAD (scrolls to the top of the page, which I dont want):
<a class="nav-link" data-toggle="tab" href="#tour" role="tab">TOUR</a>

 <script>  
$('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var $target = $(this.hash);
      $target = $target.length ? $target : $('[name=' + this.hash.slice(1) +']');

      if ($target.length) {
        var baseMinScrollTime = 500,
            baseMaxScrollTime = 900;

        var docHeight = $(document).height(),
            triggerTop = $(this).offset().top,
            targetTop = $target.offset().top;

        var scrollProportion = (targetTop - triggerTop) / docHeight,
            relativeTime = ((baseMaxScrollTime - baseMinScrollTime) * scrollProportion) + baseMinScrollTime,
            // Create inverse relationship (quicker the further we scroll)
            scrollTime = -1 * (1 - relativeTime);

        $('html, body').animate({
          scrollTop: targetTop - 10
        }, scrollTime);
        return false;
      }
    }
  });
</script>

Solution

  • You can mention the links that you want to avoid in the .not part from your code:

    For example if you want to avoid link named "home", then use:

    $('a[href*="#"]')
    :not('[href="#home"]')
    :not('[href="#anotherLinkToSkip"]')
    :not('[href="#yetAnother"]').click(function(){
          //your logic here
    })
    

    The :not helps you select everything specified before it while excluding what is specified after it. You can append more not blocks to specify more elements to exclude. More info here