简体   繁体   中英

Make a div appear when scrolling past a certain point of a page

My goal is to make a fixed div appear at the top of a page once someone scrolls a certain amount of pixels down the page. Basically once the header section is out of view, this div will appear.

I've looked at code similar to what I want; however, haven't seen anything that would allow me to easily modify the pixel count from the top of the page (if possible).

Here is a piece of code I saw dealing with making divs appear by scrolling.

// 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();

I just want to know how to make it appear. If someone knows of a piece of code already in tact with a slide up and slide down animation, that would be greatly appreciated as well but not required.

window.addEventListener("scroll",function() { 
   if(window.scrollY > 500) {
      $('.fixedDiv').slideDown();
   }
   else {
      $('.fixedDiv').slideUp();
   }
},false);

Brandon Tilley answered my question in a comment...

You would change the first line, with the startY, to be the specific Y position you need, rather than calculating based on the header's position and height. Here's an updated fiddle: jsfiddle.net/BinaryMuse/Ehney/1

window.addEventListener("scroll",function() { 
   $('.fixedDiv')[(window.scrollY > 500)?"slideDown":"slideUp"]();
},false);

DEMO: http://jsfiddle.net/DerekL/8eG2A/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM