Problem setting up a 'sticky' menu

I’m trying to set up a ‘sticky’ menu which will remain at the top of the window irrespective of scrolling. I could just have ‘position: fixed’, of course, but I’d like to inject a bit more interest.

What I’d like to happen is that when the page is first scrolled the menu goes up (out of sight) and then moves smoothly down by means of an animation, to stop at the top of the window and remain there despite further scrolling. I have almost achieved this with some very simple JS (no jQuery), You can see a demo here.
This is the script (currently in the page head:

		window.onscroll = scrollnav;

		function scrollnav() {
			var nav = document.getElementById('nav');
			var scroll = window.scrollY;
			if (scroll > 100) {
				var navscroll = 0;
				while (navscroll < scroll) { = navscroll + 'px';
			} else { = 0;


The (relevant) CSS is;
	nav {
		clear: both;
		position: absolute;
		top: 0;
		width: 100%;
		height: 2em;

However, I would like the menu to reappear more slowly (it’s almost instantaneous here). I have tried adding a jQuery animation, but it brings other problems in its wake:

$(document).ready(function() {
	alert ('document ready');
//	Obtain the height of <nav>
//Use outerHeight() instead of height() if padding
	var navHeight = $('#nav').outerHeight();

//when to scroll
		$('#nav').css('opacity', 0);
//		if ($(window).scrollTop() > navHeight){
			$("#nav").animate({"top": ($(window).scrollTop() + 5) + "px"},{
				queue: false,
				duration: 1000,
				complete: function() {
					$('#nav').css('top', 5 + 'px');
					$('#nav').animate({'opacity': 1}, 2500);
//		} else {
//			$('#nav').removeClass('fixed');
//			$('#nav').css('top', 0);
//		}



I think I have managed to get the animation to complete before the subsequent statements are executed. The main problem is that the menu moves too far down the page before jumping back to the top. The value of ‘$(window).scrollTop()’ is supposed to be the (total or accumulated) distance that the page has scrolled up, so by making that the value of the ‘top’ position of the menu should bring the menu to the top of the window. But it’s much further down. It’s as if the ‘top’ position of the menu were being calculated from the top of the window instead of the top of the page. You can see a demo here

Can anyone tell me how I can correct this, please ?