javascript - Smooth scroll to div id jQuery

ID : 10250

viewed : 36

Tags : javascriptjqueryscrolljavascript

Top 5 Answer for javascript - Smooth scroll to div id jQuery

vote vote

100

You need to animate the html, body

DEMO http://jsfiddle.net/kevinPHPkevin/8tLdq/1/

$("#button").click(function() {     $('html, body').animate({         scrollTop: $("#myDiv").offset().top     }, 2000); }); 
vote vote

89

If you want to override standard href-id navigation on the page without changing the HTML markup for smooth scrolling, use this (example):

// handle links with @href started with '#' only $(document).on('click', 'a[href^="#"]', function(e) {     // target element id     var id = $(this).attr('href');      // target element     var $id = $(id);     if ($id.length === 0) {         return;     }      // prevent standard hash navigation (avoid blinking in IE)     e.preventDefault();      // top position relative to the document     var pos = $id.offset().top;      // animated top scrolling     $('body, html').animate({scrollTop: pos}); }); 
vote vote

71

here is my 2 cents:

Javascript:

$('.scroll').click(function() {     $('body').animate({         scrollTop: eval($('#' + $(this).attr('target')).offset().top - 70)     }, 1000); }); 

Html:

<a class="scroll" target="contact">Contact</a> 

and the target:

<h2 id="contact">Contact</h2> 
vote vote

60

Plain JS:

Can be done in plain JS if you use modern browsers.

document     .getElementById("range-calculator")     .scrollIntoView({ behavior: "smooth" }); 

Browser support is a bit issue, but modern browsers support it.

vote vote

60

one example more:

HTML link:

<a href="#featured" class="scrollTo">Learn More</a> 

JS:

  $(".scrollTo").on('click', function(e) {      e.preventDefault();      var target = $(this).attr('href');      $('html, body').animate({        scrollTop: ($(target).offset().top)      }, 2000);   }); 

HTML anchor:

  <div id="featured">My content here</div> 

Top 3 video Explaining javascript - Smooth scroll to div id jQuery

Related QUESTION?