Advertisement Slide-In

(JQuery) Animate an element sliding in & out of the page once a user scrolls down to certain points on the page.

by Don Schaefer

HTML

<div id="header">Header</div>
<div id="main">Main</div>
<div id="footer">Footer</div>
<div id="slideAd">Slide Ad</div>

CSS

html, body {
    margin: 0;
    padding: 0;
}
#header, #main, #footer {
    width: 100%;
    padding: 10px;
    border: 1px solid #444;
}
#header, #footer {
    height: 100px;
}
#main { 
    height: 500px;
}
#slideAd {
    height: 75px;
    width: 360px;
    border: 1px solid #ff0000;
    position: fixed;
    top: 0;
    right: -360px; /*Set to 0 to show the ad initially or set to -360px to hide the ad until the user starts scrolling down*/
}

JavaScript

//Self-contained function to avoid potential conflicts with other scripts
$(function(){
    //Cache relevant objects
    var $window = $(window);
    var $slideAd = $('#slideAd');
    //Calculate the # of pixels between the top of the page & the start of the footer, then subtract the height of the browser window so that the final value is the amount the user would need to scroll in order to start seeing the footer
    var endZone = $('#footer').offset().top - $window.height();
    
    //Whenever the user scrolls...
    $window.on('scroll', function(){
        //Check to see if the total amount scrolled is greater than 'endZone'
        if($window.scrollTop() > endZone){
            //If it is, then tell #slideAd to stop anything it might be doing & then exit stage right (over the course of 250 milliseconds)
            $slideAd.stop(true).animate({'right': '-360px'}, 250);
        }else{
            //If it's not, then tell #slideAd to enter stage right (over the course of 250 milliseconds)
            $slideAd.animate({'right': '0'}, 250);
        }
    });
});