0

Need a smooth scroll in given code for a single page website, using tag it is working well but the effect is not smooth.

$('ul.nav-main').find('a').click(function() {
  var $href = $(this).attr('href');
  var $anchor = $('#' + $href).offset();
  window.scrollTo($anchor.left, $anchor.top);
  return false;
});
ul {
  list-style: none;
  margin-bottom: 100px;
}

li {
  padding: 5px 15px;
}

div {
  height: 500px;
  margin-bottom: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="#div1">Div 1</a></li>
  <li><a href="#div2">Div 2</a></li>
  <li><a href="#div3">Div 3</a></li>
</ul>


<div id="div1" style="background: red;">
  Div 1
</div>

<div id="div2" style="background: green;">
  Div 2
</div>

<div id="div3" style="background: blue;">
  Div 3
</div>
Zenoo
  • 12,670
  • 4
  • 45
  • 69
Adam Pavlov
  • 307
  • 4
  • 17

1 Answers1

0

try this

$(document).ready(function() {
  $("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;
      });
    }
  });
});
ul {
  list-style: none;
  margin-bottom: 100px;
}

li {
  padding: 5px 15px;
}

div {
  height: 500px;
  margin-bottom: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li><a href="#div1">Div 1</a></li>
  <li><a href="#div2">Div 2</a></li>
  <li><a href="#div3">Div 3</a></li>
</ul>


<div id="div1" style="background: red;">
  Div 1
</div>

<div id="div2" style="background: green;">
  Div 2
</div>

<div id="div3" style="background: blue;">
  Div 3
</div>
sanoj lawrence
  • 951
  • 5
  • 29
  • 69
  • This is as I expected but I need it in my code $('ul.nav-main').find('a').click(function(){ var $href = $(this).attr('href'); var $anchor = $('#'+$href).offset(); window.scrollTo($anchor.left,$anchor.top); return false; }); – Adam Pavlov Aug 30 '18 at 07:48