Search code examples
jqueryscrollfade

Scroll div with jquery, fade out when footer is reached


I have a long page of content that I'd like to make a toolbar for that would scroll with and hover over the top of the page. I have managed to get that done, however I need to also make it so that once the footer div is reached on scroll, that the div that is hovering will fade out. Here is what I have done so far:

function sticky_relocate() {

var window_top = jQuery(this).scrollTop();
var div_top = jQuery('#anchor').offset().top;
var footer_top = jQuery('.footer-container').offset().top;
//var length = jQuery('.main').height() - jQuery('#fixed-toolbar').height() + jQuery('.main').offset().top;
//var height = jQuery('.main').height() + 'px';

if (window_top > div_top) {
    jQuery('#fixed-toolbar').addClass('fixed');
} else if (window_top > footer_top) {
    jQuery('#fixed-toolbar').removeClass('fixed');
} else {
    jQuery('#fixed-toolbar').removeClass('fixed');
}

//console.log(height);
}

jQuery(function () {
jQuery(window).scroll(sticky_relocate);
sticky_relocate();
});

Here is a rough representation of my html:

<div id="anchor">
    <div id="fixed-toolbar">
        This is a test
    </div>
</div>

<div>
    Static text blocks<br> 
</div>

<div class="footer-container">
    This is the footer<br>
</div>

Can you tell me where I'm going wrong? I can't figure out how to fade out the scrolling div once the 'footer-container' div is reached.

I have created a JSFiddle, here's the link: http://jsfiddle.net/5bcaz88p/1/


Solution

  • Here you are a working example http://jsfiddle.net/5bcaz88p/2/

    Your else/if conditions were false, basically as you have them it will never go in the second if (if (window_top > footer_top) ) because window_top will always satisfy the first condition (it will be bigger than div_top) and it will never go to the second if. The second if should be as a separate condition :)

    function sticky_relocate() {
    
        var window_top = jQuery(this).scrollTop();
        var div_top = jQuery('#anchor').offset().top;
        var footer_top = jQuery('.footer-container').offset().top;
    
        if (window_top > div_top) {
            jQuery('#fixed-toolbar').addClass('fixed');
        } else {
            jQuery('#fixed-toolbar').removeClass('fixed');
        }
    
        if (window_top > footer_top) {
            jQuery('#fixed-toolbar').removeClass('fixed');
        }
    
    }
    
    jQuery(function () {
        jQuery(window).scroll(sticky_relocate);
        sticky_relocate();
    });