Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS/HTML : how to make something become absolute positioned once you scroll by it

Tags:

html

jquery

css

I'm new to CSS and HTML here and I'm trying to learn how to make something become absolutely positioned once you scroll by it on the page.

Here's an example of what I mean: http://fab.com/help/ (you don't need an account to scroll). When you scroll down, the black menu bar at the top disappears and the white menu bar with "How can we help you" becomes absolutely positioned.

I created a an example with a similar menu system,

http://jsfiddle.net/jkdbP/

but I don't know where to start to make it become absolutely positioned once it's scrolled by, thanks a lot for any insights!

like image 367
trying_hal9000 Avatar asked Nov 23 '11 21:11

trying_hal9000


People also ask

How do you make an absolute scrollable position?

You need to wrap the text in a div element and include the absolutely positioned element inside of it. Setting the inner div's position to relative makes the absolutely position elements inside of it base their position and height on it rather than on the . container div, which has a fixed height.

How would you absolutely positioned element?

An absolutely positioned element is an element whose computed position value is absolute or fixed . The top , right , bottom , and left properties specify offsets from the edges of the element's containing block. (The containing block is the ancestor relative to which the element is positioned.)

What is the difference between position fixed and absolute?

Whereas the position and dimensions of an element with position:absolute are relative to its containing block, the position and dimensions of an element with position:fixed are always relative to the initial containing block. This is normally the viewport: the browser window or the paper's page box.


1 Answers

See this jsFiddle: http://jsfiddle.net/jkdbP/2/

var menuTop = $('.menu').offset().top;
var menuClone = $('.menu').clone().addClass('fixed');

$(window).bind('scroll', function() {
    var scrollY = window.pageYOffset;

    if(scrollY > menuTop) {
        if(menuClone.parent().length === 0) {
            menuClone.appendTo($('.menu').parent());
        }
    } else if(menuClone.parent().length > 0) {
        menuClone.remove();
    }
});

You can use jQuery's .offset().top to get the Y-position of your menu, and window.pageYOffset (or document.body.scrollTop for old IE compatibility) to get the page's scroll offset. You can then handle the window's scroll event.

like image 98
Ry- Avatar answered Nov 15 '22 21:11

Ry-