Can I keep a DIV always on the screen, but not always in a fixed position?

I posted a sample as a comment, so I suppose I'll write out a full answer to this.

The markup is pretty straight-forward, but there are some important notes for each section.

HTML

<div id="page">
    <div id="header">
        <div id="header-inner"> <!-- Note #1 -->
            <img src="http://placehold.it/300x100" />
        </div>
    </div>
    <div id="content">
        <!-- Some Content Here -->
    </div>
</div>

CSS

#page {
    padding: 100px;
    width: 300px;
}

#header,
#header-inner { /* Note #1 */
    height: 100px;
    width: 300px;
}

.scrolling { /* Note #2 */
    position: fixed;
    top: 0;
}

JavaScript

//jQuery used for simplicity
$(window).scroll(function(){
  $('#header-inner').toggleClass('scrolling', $(window).scrollTop() > $('#header').offset().top);

  //can be rewritten long form as:
  var scrollPosition, headerOffset, isScrolling;
  scrollPosition = $(window).scrollTop();
  headerOffset = $('#header').offset().top;
  isScrolling = scrollPosition > headerOffset;
  $('#header-inner').toggleClass('scrolling', isScrolling);
});

Note #1

The scrolling header will be attached to the top of the page using position: fixed, but this style will remove the content from content flow, which will cause the content to jump unless its container maintains the original height.

Note #2

Styles belong in CSS, however it may be difficult to properly align some elements with their original position. You may need to dynamically set the left or right css property via JavaScript.


You'll need jQuery or the like, see my fiddle here

Edit

jQuery function, where .form is the content div and .banner is the div that is docked

$(window).scroll(function() {
    t = $('.form').offset();
    t = t.top;

    s = $(window).scrollTop();

    d = t-s;

    if (d < 0) {
        $('.banner').addClass('fixed');
        $('.banner').addClass('paddingTop');
    } else {
        $('.banner').removeClass('fixed');
        $('.banner').removeClass('paddingTop');
    }
});

.fixed {
    position:fixed;
    top:0px;
}
.paddingTop{
    padding-top:110px;
}