Floating and Following Div

28 October 2008 ~ blog javascript

I needed one of those DIVs that appears on call and then stays in view even when you scroll, until you
close it. For lack of a better name, I call it the floating following div, and it's pretty easy to make. With a little
help from Prototype we can even make it work across the major browsers.

First you need to put the div to be floated somewhere on your page. The page itself can be anything you want.

<div id="movable">This is my floating area</div>

and then you need to give it some initial style:

#movable {
    position: absolute;
    left: 100px;
    width: 200px;
    height: 200px;
    background-color: red;

Once all that is on the page, you will need some JavaScript to do the fancy stuff:

<script type="text/javascript" src="prototype.js"></script><script type="text/javascript">
        Event.observe(window,'scroll', function(evt){
            $('movable').setStyle({ top: 8 + document.viewport.getScrollOffsets().top + 'px' });

    function showDiv(evt){

This causes the "movable" element to be hidden. Once the button with an id of "showme" is clicked, the element will
be shown and will then follow along with vertical scrolling, staying up near the top of the view port. The key to this
following motion is the function mapped to the window scrolling event:

$('movable').setStyle({ top: 8 + document.viewport.getScrollOffsets().top + 'px' });

The document.viewport.getScrollOffsets() function is provided by
Prototype. It's nothing exciting, but it works... just another thing posted here for future reference.

Creative Commons License CoffeaElectronica.com content is copyright © 2016 Christopher J. Stehno and available under a Creative Commons Attribution-ShareAlike 4.0 International License.