0

Howdey!

Simple problem: I've a fixed header, the height shrinks down based on the window scrollTop-value to the half of its height.

What I have so far:

HTML

<div id="header">
    <img src="http://yckart.com/ph?text=scroll down" alt>
</div>

CSS

body{padding-top:200%} /* not really needed */

#header {
    position:fixed;
    top:0;
    left:0;
    right:0;
    height:200px;

    color:#eee;
    background:#222
}

#header img {height:100%; width:auto}

JS

var header = $('#header'),
    headerH = header.height();

$(window).scroll(function() {
    if ($(this).scrollTop() <= headerH / 2) {
        header.css({
            height: -($(this).scrollTop() - headerH)
        });
    }
}).scroll();

Here's a fiddle.

Works well so far. However, if the user scrolls down e.g. to the bottom and reloads the page, the if statement doesn't work.

Any ideas how to fix it?

yckart
  • 32,460
  • 9
  • 122
  • 129
  • That's because your function gets called only on scroll event, you could put the if statement into a function and call it when the javascript loads. – JanHocevar Sep 10 '12 at 11:52
  • Hmm, I thought the scroll event will triggered with `.scroll()` on pageload? But I try your proposal, thanks so far! – yckart Sep 10 '12 at 12:01
  • No improvement: http://jsfiddle.net/ARTsinn/dnz5x/3/ – yckart Sep 10 '12 at 12:04

1 Answers1

1

Nothing wrong with the if statement. You need to add an else statement for when the initial scroll state is at the bottom. E.g.:

    var header = $('#header'),
    headerH = header.height();

$(window).scroll(function() {
    if ($(this).scrollTop() <= headerH / 2) {
        header.css({
            height: -($(this).scrollTop() - headerH)
        });
    } else {
      header.css({
            height: headerH / 2
        });
    }
}).scroll();
Andrew Dyster
  • 2,278
  • 19
  • 23
  • @AndrewDyster I have a div that has padding on top, is there any way that the padding can be decreased as well to keep the content centered vertically? – Zach Starnes Jul 01 '13 at 19:38