Friday
Nov162012
Easy Scroll-Aware Hovering HTML Container with jQuery
Friday, November 16, 2012 at 9:23AM
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);
Kevin | Post a Comment |
tagged JQuery, JavaScript in JavaScript
Reader Comments