Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 665
kdjernigan Avatar asked Nov 25 '12 07:11

kdjernigan


People also ask

How do I keep my div visible when scrolling?

You need to put position: fixed; on the div element. That will anchor it to the viewport.

How can I make a div fixed after scrolling a certain amount?

Method 1: Using the sticky value of the position property The 'sticky' value of the position property sets an element to use a 'relative' position unless it crosses a specific portion of the page, after which the 'fixed' position is used.

How do I automatically scroll a div?

How do you make a div scrollable in HTML? For a scrollable bar, use the x and y-axis. Set the overflow-x: hidden; and overflow-y: auto; to automatically hide the horizontal scrollbar and show a vertical scrollbar.

How do I scroll to a specific div in HTML?

The scrollIntoView method: The scrollIntoView() is used to scroll to the specified element in the browser. Example: Using scrollIntoView() to scroll to an element.


2 Answers

window.addEventListener("scroll",function() { 
   if(window.scrollY > 500) {
      $('.fixedDiv').slideDown();
   }
   else {
      $('.fixedDiv').slideUp();
   }
},false);
like image 89
lostsource Avatar answered Nov 04 '22 16:11

lostsource


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

like image 26
kdjernigan Avatar answered Nov 04 '22 14:11

kdjernigan