10

I have a scrolltotop icon that appears when the window is scrolled down a bit. The thing is when the window is scrolled to the bottom of the page it overlaps a div which I do not want.

I would like to make it so the top position of scrolltotop gets animated upwards just a bit to avoid colliding with the div when the window is scrolled all the way to the bottom

Here's what I have so far: https://jsfiddle.net/qn6h9qad/

jQuery:

    //Scroll to top animate in
$(window).scroll(function(){
    if ($(this).scrollTop() < 300) {
        $('.scrollToTop').fadeOut(1000).css({right:-70});

    } else {
        $('.scrollToTop').fadeIn(1000).css({right:20});
    }
});

//Click event to scroll to top
$('.scrollToTop').click(function(){
    $('html, body').animate({scrollTop : 0},1000);
    return false;
});

2 Answers 2

5

You need to add an extra condition to the scroll event on the window:

if(($(this).scrollTop() + $(this).height()) > $('.projnav').position().top){
    $('.scrollToTop').css(bottom, 40);
}
else{
    $('.scrollToTop').css(bottom, 20);
}

To make the animation smooth just add:

.scrollToTop{
    transition: all .5s;
}

Fiddle working: http://jsfiddle.net/qn6h9qad/5/

1
  • 1
    Cool this works, is there a way to make it animate to the position instead of jumping? Commented Apr 24, 2015 at 3:56
0

Try

//Scroll to top animate in
$(window).scroll(function(){
    if ($(this).scrollTop() < 300) {
        $('.scrollToTop').stop(true, true).fadeOut(1000)
        .css({right:-70, bottom:"20px"});

    } else {
        $('.scrollToTop').fadeIn(1000)
        .css({right:20, bottom:"40px"});
    }
});

//Click event to scroll to top
$('.scrollToTop').click(function(){
    $('html, body').animate({scrollTop : 0},1000);
    return false;
});

jsfiddle https://jsfiddle.net/qn6h9qad/4/

3
  • There is a problem when you scroll up and down, since 1.5 is bigger than .75, at some point the $('.scrollToTop') will be up the windows ;) Commented Apr 24, 2015 at 3:54
  • after reaching the bottom, if you scroll upwards again its getting messed up
    – Dhiraj
    Commented Apr 24, 2015 at 3:54
  • 1
    @guest271314: But in this case you don't need jQuery to do this, you could do it changing the bottom: 40px; in .scrollToTop Commented Apr 24, 2015 at 4:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.