Page with Smooth Scroll

Asked

Viewed 2,537 times

0

I’m linking the pages to make a smooth scroll between the internal links but it’s not working.

Javascript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript">
      $('nav a').click(function(e)){
      e.preventDefault();
      var id = $(this).attr('href');
        targetOffset = $(id).offset().top;
      $('html, body').animate({
        scrollTop:targetOffset
      },500)

      }
      </script>

HTML MENU

<header>
        <div class="menu">
            <nav>
              <ul>
                <li><a href="index.html" >página principal</a><i class="fas fa-home fa-2x" title="Página Principal"></i></li>
                <li><a href="#atendimento" >atendimento</a><i class="fas fa-book-reader fa-2x" title="Atendimento"></i></li>
                <li><a href="#sobremim" >sobre mim</a><i class="far fa-smile fa-2x" title="Sobre mim"></i></li>

            </ul>
        </nav>
        </div>
        </div>
</header>

HTML CONTENT

<div class="row featurette">
          <div class="col-md-7 order-md-2" id="sobremim">
            <h2 class="featurette-heading" id="sobremim">Sobre mim</h2>
            <p class="lead">texto</p>
          </div>
          <div class="col-md-5 order-md-1">
              <img class="bd-placeholder-img bd-placeholder-img-lg featurette-image img-fluid mx-auto" src="/img/sala.jpg">          </div>
        </div>

2 answers

5


In your CSS put the code

html {
  scroll-behavior: smooth;
}

And you won’t need Javascript code.

  • Safari does not support this property yet.

1

There is a method in HTML elements called .scrollIntoView(scrollIntoViewOptions).

With it, it is possible to make the browser scroll the page to the element. The scrollIntoViewOptions is an object that accepts the property "behavior": "smooth", that makes the browser roll smoothly up to it.

In your case, it would look like this:

$('nav a').click(function(e)){
    this.scrollIntoView({ behavior: "smooth" });
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.