Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to animate css 'top' in jQuery at a certain scroll location or when an element is visible?

Tags:

jquery

scroll

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;
});
like image 836
Robbie Fikes Avatar asked Apr 24 '15 02:04

Robbie Fikes


1 Answers

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/

like image 168
Tom Sarduy Avatar answered Sep 26 '22 15:09

Tom Sarduy