Search code examples
jqueryfadein

How to trigger a element to fadeIn first when a element is visible?


Lets say I have the div #this-div in a footer like this.

HTML:

<footer>
    <div id="this-div">
    </div>
</footer>

CSS:

footer {
    background:black;
}

#this-div {
    height:50px;
    width:50px;
    background:red;
    margin:0 auto;
    display:none;
}

And then I fadeIn #this-div with jQuery like this:

$( document ).ready( function() {
$( '#this-div' ).fadeIn( 'slow' );
});

But now. Lets say I got alot of content on my website and the footer is a few scrolls down. How can I trigger the fadeIn at first when <footer> is visible on the screen?

jsfiddle: http://jsfiddle.net/2ao1mfs9/


Solution

  • In order to achieve that, you need to find out the offset of your footer like this:

    var footerTop = $('footer').offset().top;
    

    Then, when the viewport reaches that distance from the top of the screen as the user scrolls, you can trigger your fadeIn effect as such:

    $(window).scroll(function(){
        if($(this)).scrollTop() >= footerTop){ // adding a little more to the footerTop's value may give a better feeling.
            $( '#this-div' ).fadeIn( 'slow' );
        }
    });