Dynamic Header (Fixed Position)
Dynamic Header (Fixed Position)
HTML
<body>
<div style="width:1000px;height:1000px;border-style:solid;border-color:blue;border-width:1px;">
<div id="homeheader">
<p> My y is fixed but my x is supposed to be absolute, and it is, but when the window is bigger than me, I should stay centered instead of moving all the way to the left of the page as soon as you try to scroll.</p>
</div>
</div>
</body>
CSS
body {
width: 800px;
margin-top: 20px;
margin-bottom: 20px;
margin-left: auto;
margin-right: auto;
padding-left: 20px;
padding-right: 20px;
border-style: solid;
border-color: red;
border-width: 1px;
}
div#homeheader {
width:800px;
height: 120px;
position: fixed;
background: gray;
}
JavaScript
var headeroffset;
var header = $('#homeheader');
// handle scroll
$(window).scroll(function() {
// auto when not defined
if (headeroffset === undefined) {
// capture offset for current screen size
headeroffset = header.offset();
}
// calculate offset
var leftOffset = headeroffset.left - $(this).scrollLeft();
// set left offset
header.css('left', leftOffset);
});
// handle resize
$(window).resize(function() {
// remove left setting
// (this stops the element from being stuck after a resize event
if (header.css('left') !== 'auto') {
header.css('left', '');
headeroffset = undefined;
}
});