vladchooo
vladchooo

Reputation: 3

jQuery animate help

I wnat to scroll slowly a elemnt, to create a scroll animation effect. I have this code:

See here.

Scroll to see. I want the red box to scroll slowly when I scroll the page. But now it's maded to scroll only down with +50px but when you scroll up the red box go up but slowly...

Thanks previously!

Upvotes: 0

Views: 388

Answers (3)

redsquare
redsquare

Reputation: 78667

See my example fiddle here. Important thing here is to ensure you use a setTimeout to avoid a massive build up events since the window scroll event gets called lots of times depending how a user scrolls.

code

var scrollId;

$(document).scroll(scrollme);

function scrollme(){
    window.clearTimeout(scrollId);
    scrollId = window.setTimeout(scroll, 25);
}

function scroll(){
     $(".block").stop().animate({"top": ($(window).scrollTop()) + 30 + "px"}, 550);
}

Upvotes: 1

Harun
Harun

Reputation: 5179

Try the following Jquery plugin,

http://www.smoothdivscroll.com/

Hope this helps...

Upvotes: 0

Kevin Bowersox
Kevin Bowersox

Reputation: 94459

This example will allow the div to scroll back up the page as the user scrolls up: http://jsfiddle.net/CJXEX/1/

$(document).scroll(function(event){
   var direction = scrollFunc(event);
    $(".block").animate({"top": "direction" + "=1px"}, "slow");
4});

//Source: http://stackoverflow.com/questions/1222915/can-one-use-window-onscroll-method-to-include-detection-of-scroll-direction
function scrollFunc(e) {
    if ( typeof scrollFunc.x == 'undefined' ) {
        scrollFunc.x=window.pageXOffset;
        scrollFunc.y=window.pageYOffset;
    }
    var diffX=scrollFunc.x-window.pageXOffset;
    var diffY=scrollFunc.y-window.pageYOffset;

    if( diffY<0 ) {
        return "-";
    } else if( diffY>0 ) {
        return "+";
    } else {
        return "-";
    }
    scrollFunc.x=window.pageXOffset;
    scrollFunc.y=window.pageYOffset;
}

Upvotes: 0

Related Questions