Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fixed/floating div element when scrolling

I'm trying to search for this on the web, but I'm not sure what to look for exactly. I'm trying to find out how to create a div element that will be fixed, or float ONLY when the TOP of the element reaches the TOP of the window browser view. For instance, if an element is half way of the page, when you continue to scroll down, that element will stay put UNTIL its about to disappear, then it would want to stay at the top of my browser (fixed).

like image 443
hellomello Avatar asked Oct 12 '11 03:10

hellomello


People also ask

How do I keep my div fixed when scrolling?

Method 1: Using the sticky value of the position property It can be given a value of '0px' to make the element leave no space from the top of the viewport, or increased further to leave space from the top of the viewport.

How do you stop DIVS from sliding when floating?

Set height and width to 100% for the bottom div and set overflow auto on the bottom div as well. Now the div will not move up to fill space.

How do you make the element not move when scrolling?

There's another way to disable scrolling that is commonly used when opening modals or scrollable floating elements. And it is simply by adding the CSS property overflow: hidden; on the element you want to prevent the scroll.


1 Answers

I think I'm doing something similar to what you want to do. Try out the following code, put whatever you need in notification div and leave the anchor one alone.

<div id="notification-anchor"></div>
<div id="notification"></div>

<script type="text/javascript"> 
    $(function() {
        var a = function() {
            var b = $(window).scrollTop();
            var d = $("#notification-anchor").offset().top;
            var c = $("#notification");
            if (b > d) {
                c.css({position:"fixed",top:"0px"})
            } else {
                c.css({position:"absolute",top:""})
            }
        };
        $(window).scroll(a);a()
    });
</script> 

Edit: You should note, this requires you to include JQuery if that's not obvious to you.

like image 57
neurotik Avatar answered Sep 19 '22 17:09

neurotik