Marc Casavant
Marc Casavant

Reputation: 299

jQuery scrollTop animation not working

The following code causes my page to animate weirdly. When the event is fired that triggers this function, html / body element drops down a few hundred pixels and then slowly glides to the top of the browser. I need the page to scroll to the top of the roi calculator element. Any ideas? This same code works perfectly on jsfiddle.

    var $roiCalculator = $(".roi-calculator");
    $(".roi-container .btn.yellow").on('click', function(){
        var offset = $roiCalculator.offset().top;

        $("html, body").animate({
            scrollTop: $(".roi-calculator").offset().top
        }, 3000);

    });

Upvotes: 1

Views: 1930

Answers (2)

Seth
Seth

Reputation: 10454

Zepto doesn't have the ability to animate scrollTop.Since all animations are done through css3, you need to add a relatively small shim, minified, or not. The developers are aware of this issue and are attempting to patch it for the next release.

var offset = $roiCalculator.offset().top;
// Is Zepto loaded?      
if ('__proto__' in {}) {
  $.scrollTo({
      endY: offset,
      duration: 3000,
    // If needed
    // callback: function() {
    // }
  });
// It's jQuery
} else {
  $('html, body').animate({
    scrollTop: offset,
  }, 3000);
};

or better yet, abstract it...

function scrollTo(offset, time) {
    if ('__proto__' in {}) {
      $.scrollTo({
          endY: offset,
          duration: time,
        // If needed
        // callback: function() {
        // }
      });
    } else {
      $('html, body').animate({
        scrollTop: offset,
      }, time);
    };
};

var offset = $roiCalculator.offset().top;
scrollTo(offset, 3000);

Upvotes: 1

Felix
Felix

Reputation: 38102

Try to wrap your code inside DOM ready handler $(function() {...}); to make sure all the DOM elements have been loaded properly before executing your jQuery code:

$(function() {
    var offset = $roiCalculator.offset().top;
    $("html, body").animate({
        'scrollTop': offset
    }, 3000);
});

Upvotes: 0

Related Questions