Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make div appear from the top when scrolling down?

I would like a div to appear and slide down once you scroll pass the header.

Here's what it should look like:

http://www.space.com/11425-photos-supernovas-star-explosions.html

Here's what I got so far but it's not working.

http://jsfiddle.net/nHnrd/

like image 609
checkenginelight Avatar asked Oct 26 '11 16:10

checkenginelight


1 Answers

You'll need to find out the height of the header and its position on the page then just show or hide the div depending on the scrollTop value using jquery.

For example:

// Get the headers position from the top of the page, plus its own height
var startY = $('header').position().top + $('header').outerHeight();

$(window).scroll(function(){
    checkY();
});

function checkY(){
    if( $(window).scrollTop() > startY ){
        $('.fixedDiv').slideDown();
    }else{
        $('.fixedDiv').slideUp();
    }
}

// Do this on load just in case the user starts half way down the page
checkY();

Then you'll just need to set the .fixedDiv to position:fixed: top: 0; left: 0;

Edit: I've added a checkY() function that you can call whenever the page loads as well as on scroll. To hide it initially though, just use CSS.

like image 152
will Avatar answered Nov 14 '22 23:11

will