Kakadela Horosho Kakadela Horosho - 2 months ago 9
Javascript Question

Smooth scroll using jquery

I have html page and menu

Menu :

<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li>
<a href="#info">info</a>
</li>
...
</ul>
</div>


Part of content :

<div id="info" class="row">
<div class="col-lg-12">
<h1>Title</h1>
<p>Lorem Ipsum</p>
</div>
</div>


And I want to add smooth page scroll to an anchor. So I tried:

$(document).ready(function($) {

$('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) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});

});


But it doesn't work. And scroll isn't smooth.

Answer

Replace your jQuery function with this:

$(function() {
$('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) {
    $('html, body').animate({
      scrollTop: target.offset().top
    }, 1000);
    return false;
  }
}
});
});
Comments