html – jQuery Scroll to Div

html – jQuery Scroll to Div

It is often required to move both body and html objects together.

$(html,body).animate({
   scrollTop: $(#divToBeScrolledTo).offset().top
});

ShiftyThomas is right:

$(#divToBeScrolledTo).offset().top + 10 // +10 (pixels) reduces the margin.

So to increase the margin use:

$(#divToBeScrolledTo).offset().top - 10 // -10 (pixels) would increase the margin between the top of your window and your element.
$(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;
      }
    }
  });
});

Check this link: http://css-tricks.com/snippets/jquery/smooth-scrolling/ for a demo, Ive used it before and it works quite nicely.

html – jQuery Scroll to Div

Something like this would let you take over the click of each internal link and scroll to the position of the corresponding bookmark:

$(function(){
  $(a[href^=#]).click(function(e){
    var name = $(this).attr(href).substr(1);
    var pos = $(a[name=+name+]).offset();
    $(body).animate({ scrollTop: pos.top });
    e.preventDefault();
  });
});

Leave a Reply

Your email address will not be published.