Back to top button just scroll to top

1

I have the following question. I created a simple button to go back to the top of the page:

<a href="page-top" class="back-to-top">Back to Top</a>  

    <script>
        $(document).ready(function(){
            var btt = $('.back-to-top');
            btt.on('click', function(e){
                $('html, body').animate({
                    scrollTop:0
                    }, 500);

                    e.preventDefault();
                });

            $(window).on('scroll', function(){
                var self = $(this),
                    height = self.height(),
                    top = self.scrollTop();

                if(top > height){
                    if(!btt.is('#page-top:visible')){
                        btt.fadeIn();
                        }
                    } else{
                        btt.hide();
                        }
                });
            });
    </script>

However, I would like to apply the same effect to the facebook button for mobile, where the button will only appear when I scroll the scroll up. How?

    
asked by anonymous 23.02.2015 / 18:58

2 answers

1

It does, but I suggest you take a look at this plugin:

link

I think it should help you.

If it does not help, explain better what mobile button is that of facebook ...

    
23.02.2015 / 21:07
0

Yes, you can do it in two ways:

1- Using the% wrapper attribute of the scroll event:

$('body').bind('mousewheel DOMMouseScroll', function(e){
    if (e.originalEvent.wheelDelta) {
        var delta = e.originalEvent.wheelDelta;
    } else {
        var delta = e.originalEvent.detail * (-40);
    }
    if (delta > 0) {
        // scroll para cima
        $('.back-to-top').fadeIn();
    } else {
        // scroll para baixo
        $('.back-to-top').fadeOut();
    }

Note: delta and DOMMouseScroll are for Firefox. ( doc )
e.originalEvent.detail and mousewheel are for other browsers . ( doc )

[EDIT]
As @Sergio warned me, the direction of the scroll is different in different browsers and in different OS. So I'll leave a link here to a great answer in relation to this. But solution 2 is still valid.

2 - Saving the position to each scroll and comparing with the previous:

var lastScroll = 0;
$(window).scroll(function(e){
    var currentScroll = $(this).scrollTop();
    if (currentScroll < lastScroll){
        // scroll para cima
        $('.back-to-top').fadeIn();
    } else {
        // scroll para baixo
        $('.back-to-top').fadeOut();
    }
    lastScroll = currentScroll;
});

Comparison

In performance, I do not know how to respond, but I believe there is no big difference. In solution 1, both events are not standardized, so they should be well tested in different browsers. Solution 2 would be the most "manual" and perhaps the most obvious one to think about. For your problem, I would use Solution 2, which is simple and you are sure to work in any environment.

    
23.02.2015 / 20:57