Floating panels

More often than not, you see certain contents of a website floating down with you as you scroll down the page. This is an utterly useful technique if you want to emphasize certain things on a web page more than others. It is also a clean way to handle empty space on a web page.

The header bar of this web page serves as a simple example of this technique. Leading social-networking platforms such as Facebook and Twitter do the same with their navigation bar. In this case, having such a functionality aids easy navigation within the site. Other examples include that of tech media websites, which always keep a floating user activity panel prompting you to like them, tweet them, etc.

So how do you actually do it?

It's Simple!
Refer to the floating panel on the right

The crux of this "floating" panel lies within its css positioning. We need to set the element's position to fixed, but only once it is off the screen

The problem can be broken down into two steps

  • Determining when the element you want to float goes of the screen
  • Setting the element's position accordingly

HTML

<div id="floating_panel">
// contents of panel
</div>

CSS

.panel_fixed {
position: fixed;
// this top property varies based on what offset you want the element to float at from the top of the screen
top: 50px;
}

jQuery

// Note that this code needs to be placed after the document is ready
// find the height offset between the top of the page, and the element's top
var top = $('#floating_panel').offset().top-parseFloat($('#floating_panel').css('margin-top'))
// the scroll event
$(window).scroll(function (event) {
// determine the current scroll position relative to the window
currentScrollPos = $(this).scrollTop();
if (currentScrollPos>=top) {
// scrolled past element, add the fixed class to the element
$('#floating_panel').addClass('panel_fixed');
} else {
// remove class otherwise
$('#floating_panel').removeClass('panel_fixed');
}
});

Let's float this

I am a Computer Engineering Student at the University of Waterloo.

I will be completing my 2nd year studies in August this year. Feel free to contact me for engineering projects, job requirements, or simply to know what's up.


Find me on LinkedIn
For a more professional network

Send me an email
About anything relevant!