Newbie
Newbie

Reputation: 2825

How can I fix the position of an element when it reaches a certain location in a webpage?

Forgive me if this question is too silly. I am making a webpage on which I will have a header that consists of two parts(upper and lower). When I scroll down the page, I want the lower part of the header still stay here. How can I implement this? I plan to write a javascript to handle this - once the lower part reach (0, 0), its position is changed to absolute from relative. I think this is gonna work but I am just wondering if there exist a better and simple way to do it. Thank you!

Upvotes: 1

Views: 88

Answers (2)

Joseph
Joseph

Reputation: 119897

check this in action: http://jsfiddle.net/JLETx/4/

UPDATE: fixed the "jumping content"

HTML

<div id="topHeader">top header</div>
<div id="bottomHeader">bottome header</div>
<div id="extremelyLongContent"> long content here </div>

JS

var initial = $('#bottomHeader').offset();

$(document).scroll(function() {
if ($(this).scrollTop() > initial.top) {
    $('#bottomHeader').css('position', 'fixed');
    $('#topHeader').css('margin-bottom', initial.top+'px');
    $('#bottomHeader').css('top','0'); 
}
else {
    $('#bottomHeader').css('position', 'static');
    $('#topHeader').css('margin-bottom', 0);
}

});

CSS

body{
position:relative;
}

#topHeader{
background:red;
height:100px;
}
#bottomHeader{
background:blue;
height:100px;
width:100%;
}

#extremelyLongContent{
background:green;
height:1000px;

}

Upvotes: 2

imjared
imjared

Reputation: 20584

Check out jQuery Waypoints. Sounds like it could come in handy for you.

Upvotes: 0

Related Questions