Gerard Clos
Gerard Clos

Reputation: 1120

Scrolling down to a position with jQuery

Hi just a quick doubt that's driving me mad.

I'm trying to automaticly scroll down to an button when this button is clicked.

I've got the y-index value of my button saved on a variable called scrollIndex (thanks to the offset() method).

And now I'm trying to scroll down my window with this:

var scrollIndex = $('#tourbutton').offset();
$("body").animate({scrollTop:(scrollIndex.top)},500,"linear");

I've actually tried a lot of things but nothing seems to work and I supose it's because I'm making a wrong use of the scrollTop method()..

Any help ? Thank you!

My full code:

window.onload = initAll; 

function initAll() { 
    changeStyle(); 
    $('#tourbutton').click = hello(); 
} 

function hello() { 
    var scrollIndex = $('#tourbutton').offset(); 
    $("html, body").animate({scrollTop:(scrollIndex.top)},800,"swing"); 
    //var scrollIndex = $('#tourbutton').offset();     
    //$("window").scrollTo({top:scrollIndex},800); 
}

SOLVED! I just wrote everything inside click() like this:

function initAll() {
$('#tourbutton').click(function() {

var scrollIndex = $('#tourbutton').offset();
$("html, body").animate({scrollTop:(scrollIndex.top)},800,"swing");

//var scrollIndex = $('#tourbutton').offset();
//$("window").scrollTo({top:scrollIndex},800);
});

    changeStyle();
}

And everything works now except I don't quite understand why... if somebody understands why I cannot link the click eventHandler to an external function I'll be glad to know the answer.

Thanks to all!

Upvotes: 2

Views: 3155

Answers (1)

mrtsherman
mrtsherman

Reputation: 39882

Are you testing in Chrome? I ran into another SO question at some point where if you specified a body height of 100% in Chrome then setting scroll position didn't work. You had to either put the body of your site in a scrollable div or not specify 100% height.

Try this:

var scrollIndex = $('#tourbutton').offset();
$("html, body").animate({scrollTop:(scrollIndex.top)},500,"linear");

Upvotes: 5

Related Questions