« New American Idols | Main | Refugees from the Days of the Dying Sun »
Friday
Nov162012

Easy Scroll-Aware Hovering HTML Container with jQuery

I needed a quick and easy way to have a container hover on the side of a page and update with details as the user selected options. This is a simple, jQuery-based approach to doing so. Note that the portion at the end is included if you are needing to fire the positioning from a repost in asp.net, in this instance I needed to do so as the floating container was only displayed and filled via an async event when the user selected their first item.

<!DOCTYPE HTML>
<style>
	#oHeader {height:200px;width:100%;background:lightyellow;margin-bottom:20px;} /* Not needed */
	#oAnchorObject {height:2000px;width:450px;background:lightgreen;} /* Not needed */
	#oSidebar {position:fixed;left:500px;border:1px solid #ff0000;padding:40px} /* Position and left or right value needed */
</style>

<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
	$(document).ready(function () {
		RepositionCard();
	});	
	
	$(window).scroll(function () {
		RepositionCard();
	});
	
	function RepositionCard() {
		try{
			var eTop = $('#oAnchorObject').offset().top;
			if (eTop - $(window).scrollTop() <= 1) {
				$("#oSidebar").css("top", 0);
			}
			else {
				$("#oSidebar").css("top", eTop - $(window).scrollTop());
			}
		}
		catch(err) {}
	}

</script>

<div id="oHeader">
	Here is some header content to show how the locking works
</div>

<div id="oAnchorObject">
	Here is your large content block to which the sidebar will orient
</div>

<div id="oSidebar">
	This will hover/stick
</div>

Optional for firing the client event after ajax postback from C#, use in page load where needed:

ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "MyScript", "RepositionCard();", true);

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>