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 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.
精彩评论