开发者

jQuery store scroll position

开发者 https://www.devze.com 2023-02-01 21:18 出处:网络
I\'ve got a couple of click statements like this $(\'.button1\').click(function() { //grab current scroll position

I've got a couple of click statements like this

$('.button1').click(function() {
//grab current scroll position  
    var currentscrollpos = $(window).scrollTop()

    $("html, body").animate({ scrollTop: 0 }, 500);

});

$('.button2').click(function() {
    //go back to scro开发者_C百科ll position
    $("html, body").animate({ scrollTop: currentscrollpos }, 500);

});

I'm not sure how to get the current scroll pos and store it in a variable so that I can use it in my other click function

Is there a way to do this?


Define the variable in the outer scope so that it's available to the other function:

var currentscrollpos;

$('.button1').click(function() {
    currentscrollpos = $(window).scrollTop()
    $("html, body").animate({ scrollTop: 0 }, 500);
});

$('.button2').click(function() {
    $("html, body").animate({ scrollTop: currentscrollpos }, 500);
});

You could and should wrap this to a closure to prevent polluting the namespace with unnecessary variables but this should get you started at least.

0

精彩评论

暂无评论...
验证码 换一张
取 消