Detect if the page is scrolling while loading the document
I use scrollTop
to detect if users scroll and then fadeIn
an item:
$(document).ready(function() {
// scroll to top
$(window).scroll(function() {
if ($(this).scrollTop() >= 700) { // if page is scrolled more than 700px
$('#return-to-top').fadeIn(200);
} else {
$('#return-to-top').fadeOut(200);
}
});
});
This works well if the user loads the page and then scrolls, but if the user is already below 700px and reloads or returns to the same page, the element is not automatically fadeIn
loaded on document load. It doesn't seem to detect that the page has already been scrolled.
Any idea what could be the problem with my code?
+3
source to share
3 answers
Just run the test when the document is ready
Better create a function
function checkScroll(){
if ($(window).scrollTop() >= 700) {
$('#return-to-top').fadeIn(200);
} else {
$('#return-to-top').fadeOut(200);
}
}
$(document).ready(function() {
checkScroll();
$(window).scroll(checkScroll);
});
+6
source to share
Just scroll to scroll after delegate.
$(document).ready(function() {
// scroll to top
$(window).scroll(function() {
if ($(this).scrollTop() >= 700) { // if page is scrolled more than 700px
$('#return-to-top').fadeIn(200);
} else {
$('#return-to-top').fadeOut(200);
}
}).scroll();
//^^^^^^ trigger scroll.
});
0
source to share