0

Hello I am new to jQuery and I have a problem! I want to scroll to the top, in a page that is loaded via AJAX call.

This works (test):

$(document).on('click', '#top_icon', function() {
    alert('ok');
});

But this is not working (this is what I want to achieve):

$(document).on('click', '#top_icon', function() {
    $('html, body').animate({scrollTop: '0px'}, 800);
});
kapantzak
  • 11,610
  • 4
  • 39
  • 61

2 Answers2

0

Try this,

$(document).on('click', '#top_icon', function() {
    $('html, body').animate({'scrollTop': '0px'}, 800);
    return false;
});

scrollTop is undefined in your case.

Jashwant
  • 28,410
  • 16
  • 70
  • 105
  • Check your errors if any. Also , do a `console.log` before and after the animate code line. – Jashwant Aug 29 '12 at 19:33
  • Sorry but I am new and I haven't used console.log before. I must search for that first! – kapantzak Aug 29 '12 at 19:39
  • Okay, do an alert before and after animate line and see if it runs. Do check for errors thrown. This line is correct and should work – Jashwant Aug 29 '12 at 19:41
  • Ok, I've done this (if correct): $(document).on('click', '#top_icon', function() { alert('ok'); $('html, body').animate({'scrollTop': '0px'}, 800); alert('ok2'); }); It alerts the two messages but does not perform the animation – kapantzak Aug 29 '12 at 19:44
  • I must have some error somewhere. It's still not working. Thanks anyway! – kapantzak Aug 29 '12 at 19:53
0

I am not sure about jQuery, but scrollTop is not a CSS property and therefor might not be part of the properties that can be animated.

But you can create a simple animation for this yourself:

var startValue = 0;
var endValue = 0;
var duration = 800;
var distance = 0;
var velocity = 0;
var step = 0;
var endTime = 0;

var animate = function() {

    var elapsedTime = new Date().getTime() - step;
    document.body.scrollTop += velocity * elapsedTime;
    step = new Date().getTime();

    if (step > endTime)
        document.body.scrollTop = endValue;
    else
        setTimeout(animate, 15);

}

    yourButton.onclick = function() {

        startValue = document.body.scrollTop;
        distance = endValue - startValue;
        velocity = distance / duration;
        step = new Date().getTime();
        endTime = step + duration;
        animate();   

    };

​ Here is a fiddle: http://jsfiddle.net/pXvQG/12/, animate by scrolling down and click the body.