Novice to Ninja Chap 3: Floating Nav

I’m having trouble with Sitepoint’s jQuery book, coding a floating sidebar that following the user as he scrolls down the page. As far as a can see I’ve replicated the necessary HTML, jQuery and CSS. But it’s still not working…

<html>
<head><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US"><head profile="http://gmpg.org/xfn/11">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<style>
	#container {
		width:650px;		
		margin: 0 auto;
	}
	
	#nav {
	position:relative;
	float:right;
	top:0px;
	width:150px;	
	}
	
	#leftContent {
		width:500px;
		height:1000px;
		padding:5px;
	}
</style>

<script type="text/javascript" language="javascript">
	$(document).ready(function(){
		  $(window).scroll(function () { 
		    $('#nav').css('top', $(document).scrollTop()); 
		  });
		});
</script>

<script type="text/javascript" src="../jqueryCode/code/lib/jquery-1.4.min.js"  ></script>
<script type="text/javascript" src="../jqueryCode/code/lib/jquery-ui-1.7.2.custom.min.js"></script>
<body>
<div id="container">

<div id="nav" style="top:0px;">
	<ul>
		<li>Home</li>
		<li>Test</li>
		<li>Test</li>	
	</ul>
</div><!-- nav -->

<div id="leftContent">
<p>Test test test test test test test test test test test test test test test test test teser ttest
Test test test test test test test test test test test test test test test test test teser ttest</p>

<p>Test test test test test test test test test test test test test test test test test teser ttest
Test test test test test test test test test test test test test test test test test teser ttest</p>
</div><!-- leftContent -->

</div><!-- container -->

</body>
</head>
</html>

You are trying to use $ before jQuery is even loaded.

Move your custom jQuery code down below the script tags that load in the jQuery library.

Thank you. I knew it would be something dumb.

Thanks again for the answer to my question. I do have one more question about this technique which I expect should also have a simple answer, how do you keep this floating navigation div from overlapping with your footer and header divs.

I’ve tried setting css’s bottom and top attributes. But the floating nav is not responding to these commands. -Thanks

Ahh, that gets more complicated.

Take a look at a special jQuery plugin called sticky float, which does that for you and more. The [url=“http://jsbin.com/eqihef”]demo page
shows you much of what it can do.

Very nice. This is exactly what I was looking for. The documentation page for the plugin links to the demo so apart from the code comments there aren’t any instructions to get it to work, but I think I can get it working with a little tinkering. Thank you, Paul.