How to make a div "stick" to the top of the page using jQuery?
<p>I'm trying to make one of those things similar to the stackoverflow orange messages at the top, if you scroll down the page the message gets fixed to the top" and when you are scrolled back up for it to be in view it resumes being fixed and goes back to being displayed as block.</p>

<p>Anyway here is my attempt:</p>

<p><a href="http://jsfiddle.net/cXP2y/" rel="nofollow">http://jsfiddle.net/cXP2y/</a></p>

<p>HTML:</p>

<pre><code>&lt;div style="border:1px solid red;height:50px;width:100%"&gt;Header&lt;/div&gt;
&lt;div id="message"&gt;Message&lt;/div&gt;

&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;
</code></pre>

<p>CSS:</p>

<pre><code>#message { padding: 10px; background: #06c; }
.message-fixed { position: fixed; top: 0; width: 100%; }
</code></pre>

<p>jQUery:</p>

<pre><code>$(function() {

var message = $('#message');
$(window).scroll(function() {
    if($(window).scrollTop() &gt; (message.offset().top + message.height())) {
        message.addClass('message-fixed');
    }
    else {
        message.removeClass('message-fixed');
    }
});

});
</code></pre>

<p>As you can see it has that flicker happening. How can I prevent this?</p>

<p>Also is there a more optimized way to write my code?</p>
