The Dude man
The Dude man

Reputation: 413

JQuery hide button when scrolling to top of window

Do I need to wrap the anchor in a div, and then use the div id for the fade? If $(this) is for #scrollToTop can I somehow use this.fade? I cannot seem to get this simple JQuery to take effect. I would like to hide #scollToTop until scrolled. Should I be wrapping this in a div and manipulating the div?

<a href="#" id="scrollToTop"></a>


$(window).scroll(function() {
    if ($(this).scrollToTop() > 75) {
        $('#scrollToTop').fadeIn();
    } else {
        $('#scrollToTop').fadeOut();
    }
});​

Upvotes: 0

Views: 1526

Answers (1)

random_user_name
random_user_name

Reputation: 26160

The reason you aren't getting it to work is due to errors in your code.

Tip: learn to use you're browser's developer console - it is an absolute necessity when developing in javascript. You had an error - scrollToTop is not a function. (You wanted scrollTop). That was the majority of the problem.

To answer your questions:

In jQuery, $(this) refers to the element that triggered the event. Therefore, in your code, $(this) refers to $(window), and therefore $(this).scrollTop is measuring the scrollTop position of the window (the same as writing $(window).scrollTop).

Since it's not referencing #scrollToTop, then no, you cannot use $(this).fade to hide the button. You are doing it properly.

No, you do not need to wrap it in a div and manipulate that.

Additionally, I've added a trigger call to ensure the button is hidden on initial load, if the page is within the range where it should be hidden. (Trigger "triggers" the event you are watching - in this case scroll - immediately, so the callback runs, and the button will be hidden / displayed as appropriate).

Here's a working jsFiddle, and the relevant code below:

$(window).scroll(function() {
    // scrollToTop is not a function - changed to scrollTop
    if ($(this).scrollTop() > 75) {
        $('#scrollToTop').fadeIn();
    } else {
        $('#scrollToTop').fadeOut();
    }
}).trigger('scroll');

Upvotes: 2

Related Questions