Domanda

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?

È stato utile?

Soluzione

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();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top