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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <!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:
1 | ScriptManager.RegisterClientScriptBlock(Page, typeof (Page), "MyScript" , "RepositionCard();" , true ); |


tagged
JQuery,
JavaScript in
JavaScript



Reader Comments