Ludwig Kristoffersson Ludwig Kristoffersson - 6 months ago 27
Javascript Question

JavaScript scroll to div with animation

I have a PhoneGap application that when it opens an HTML page, I want it to scroll to a specific

<div>
element. So far I've been able to make it do that with this script using jQuery:

<script>
$(document).delegate('.ui-page', 'pageshow', function () {
var offset = $(this).find('#timeindicatordiv').offset().top;
setTimeout(function () {
$.mobile.silentScroll(offset);
}, 0);
});
</script>


This only gives me a jump directly to the
<div>
which looks a bit choppy.

Is there any way to give this a smooth animation?

Answer

You can do the following:

var scrollToElement = function(el, ms){
    var speed = (ms) ? ms : 600;
    $('html,body').animate({
        scrollTop: $(el).offset().top
    }, speed);
}

// specify id of element and optional scroll speed as arguments
scrollToElement('#timeindicatordiv', 600);

jsfiddle/example: http://jsfiddle.net/dtR34/4/

Comments