Robby
Robby

Reputation: 827

Overriding JavaScript smooth scroll

I have this code that works fine to smoothly scroll to an anchor point on a page.

$('a[href^="#"]').click(function () {
    $('html, body').animate({
        scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
    }, 800);

    return false;
});

That works whenever I want to the smooth scrolling functionality. The problem I have is that I want to link to an anchor point without a smooth scroll for one particular link. How could I do that?

Upvotes: 1

Views: 584

Answers (1)

Diogo Peres
Diogo Peres

Reputation: 1372

Add a property for the links that you want to have smooth scroll and make the condition below. You can also make the inverse and add a property for the link that you don't want to have smooth scroll.

$('a[href^="#"]').click(function () {
     
    if($.attr(this, 'behaviour') === "smooth") {
      $('html, body').animate({
        scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
      }, 800);
    } else {
      $('html, body').scrollTop($('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top);
    }
    

    return false;
});
.section1 {
  height: 700px;
  background-color: pink;
}

.section2 {
  height: 600px;
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <h1>Smooth Scroll</h1>

  <div class="main section1" name="section1">
    <h2>Section 1</h2>
    <p>Click on the link to see the "smooth" scrolling effect.</p>
    <a behaviour="smooth" href="#section2">Click Me to Smooth Scroll to Section 2 Below</a>
  </div>

  <div class="main section2" name="section2">
    <h2>Section 2</h2>
    <a href="#section1" id="s2">Click Me to Scroll Instantaneously to Section 1 Above</a>
  </div>
</body>

Upvotes: 1

Related Questions