Domanda

I have a Scroll to top button with a Fixed position. I want this button to slide in from the bottom of the screen after you scrolled 400px. i can get it to work with fadein and fadeout. This is the code of the button.

<a href="#top" id="scrolltop"><img src="images/upbutton.png" alt="scroll to top"/></a>

#scrolltop {
position:fixed;
height:38px;
width:38px;
background-color:#444;
right:15px;
bottom:15px;
z-index:100;
} 



$(document).scroll(function() {
        var y = $(this).scrollTop();
        if (y > 1000) {
            $('#scrolltop').animate({bottom: 100});
        } else {
            $('#scrolltop').animate({bottom: -100});
        }
});
È stato utile?

Soluzione

One issue is that your are testing against 1000 instead of 400.

Besides that the scroll event is fired multiple times while scrolling. And because the animate function of jquery is stackable you end with multiple animations in each direction and long delays while waiting for each to end..

So you need a more strict logic..

  • do not animate if the element is already animating, use the :animated jquery selector combined with the .is() method
  • also check if the element is already in the correct place before trying to animate towards it, add/remove a class as a flag to do this
  • also it is a good idea to cache variables that you repeatedly use

so the script becomes

var scr = $('#scrolltop');
$(document).scroll(function () {
    var y = $(this).scrollTop();
    if (y > 400) {
        if (scr.is('.off') && !scr.is(':animated')) {
            scr.animate({bottom: 100}, function () {
                scr.removeClass('off');
            });
        }
    } else {
        if ((!scr.is('.off')) && (!scr.is(':animated'))) {
            scr.animate({bottom: -100}, function () {
                scr.addClass('off');
            });
        }
    }
});

Demo at http://jsfiddle.net/gaby/7eYdB/

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top