admin管理员组

文章数量:1323714

I'm using the scrollTop to detect if the users scrolls then fadeIn an element:

$(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);
        }
    });
});

It works well if the user loads the page and then scroll, but if the user is already below the 700px and reload or goes back to the same page the element doesn't fadeIn automatically on document load. It seems that it is not detecting the page is already scrolled.

Any idea what could be the problem with my code?

I'm using the scrollTop to detect if the users scrolls then fadeIn an element:

$(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);
        }
    });
});

It works well if the user loads the page and then scroll, but if the user is already below the 700px and reload or goes back to the same page the element doesn't fadeIn automatically on document load. It seems that it is not detecting the page is already scrolled.

Any idea what could be the problem with my code?

Share Improve this question edited Aug 5, 2015 at 10:36 propcode asked Aug 5, 2015 at 10:32 propcodepropcode 3091 gold badge5 silver badges15 bronze badges 1
  • can you post HTML? – rrk Commented Aug 5, 2015 at 10:35
Add a ment  | 

3 Answers 3

Reset to default 9

Just do the test when document is ready

It's better to 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);
});

Call this way to your function

Put this line end of your document ready.

$(window).scroll();

Simply trigger scroll after the delegation.

$(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.
});

本文标签: javascriptDetect if page is scrolled on document loadStack Overflow