Jamie Taylor
Jamie Taylor

Reputation: 3530

jQuery store 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 scroll 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?

Upvotes: 2

Views: 5324

Answers (1)

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124768

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.

Upvotes: 6

Related Questions