bonny
bonny

Reputation: 3245

jQuery window position when loading a page

I have a problem with the following jQuery function:

$(document).ready(function(){

    $(window).scroll(function(){
        if ($(window).scrollTop() + $(window).height() == $(document).height()) {
            $('.scrollToTop').fadeOut();
        } else {
            $('.scrollToTop').fadeIn();
        }
    });

    $('.scrollToTop').click(function(){
        $('html, body').animate({scrollTop : 0},800);
        return false;
    });
});

This function is to display a DIV when an user scrolls down the page. Now my problem is, that the DIV will be displayed already when the page is loaded and the window is already on top! When scrolling down the DIV stays. When clicking that DIV the window scrolls up and the DIV disappears like it should do. The problem is just that it appears after loading a page.

So I have no clue what causes that?

Thanks alot.

Upvotes: 3

Views: 211

Answers (1)

Vishwanath
Vishwanath

Reputation: 6004

Just add a fadeOut or hide initially. That should do it.

$(document).ready(function(){
    $('.scrollToTop').hide();
    $(window).scroll(function(){
        if ($(window).scrollTop() + $(window).height() == $(document).height()) {
            $('.scrollToTop').fadeOut();
        } else {
            $('.scrollToTop').fadeIn();
        }
    });

    $('.scrollToTop').click(function(){
        $('html, body').animate({scrollTop : 0},800);
        return false;
    });
});

Upvotes: 2

Related Questions