chanHXC
chanHXC

Reputation: 619

animation jQuery scrollTop doesn't work properly

Does animating the scrollTop property renders inaccurately. kindly check this code that i've made in jsbin http://jsbin.com/ewulum/2/edit

what i would like to do is when a link is clicked it would automatically scroll down to it's corresponding section. But i can't figure out what's wrong with the code on why doesn't it scroll down to the corresponding section properly. Clicking on the first two links seem to work fine.

thanks in advance.

Upvotes: 1

Views: 2506

Answers (2)

Ifeanyi Chukwu
Ifeanyi Chukwu

Reputation: 3317

Everything seems fine to me. The most relevant code to scroll to a particular element is:

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

You can add extra pixels to position it perfectly as required.

$('html, body').animate({ scrollTop: $('#box').offset().top + 10 }, 2000);

I went into your http://jsbin.com/ewulum/2/edit and made a few changes:

.wrapper {
  width: 90%;
  margin: 0 auto;
  background:#ececec;
  overflow: auto;
  height: 250px;
}

JS File

//event delegation
$("#nav-wrapper").on("click", "a", function(e){

  var cur_el_href = $(this).attr("href"),
      cur_el_top =$(cur_el_href).offset().top;

  e.preventDefault();

  console.log("The current elem's href value is " + cur_el_href);
  console.log("The target section's offset top is " + cur_el_top);

 $(".wrapper").animate({
     scrollTop:cur_el_top
   },
   800, function(){
     //this callback is for demonstration only so as not to back to top when testing other links
         $(this).animate({scrollTop:0}, 1000);
   });

});

Upvotes: 0

Hadi
Hadi

Reputation: 2905

Actually it's working and animation jQuery scrollTop working properly. Just add height:2000px to body css. When you are clicking on 3rd,4th or 5th link then it scroll down and as there's no space under section 5 so scroll stop. Add some space below it or add a height on container should solve your problem.

Upvotes: 1

Related Questions