JavaScript Floating Box Following Scroll

By Xah Lee. Date: . Last updated: .
♥♥♥♥♥ floating ♥♥♥♥♥ box ♥♥♥♥♥ something ♥♥♥♥♥

This page shows you how to use JavaScript to have a floating box that follows you to the center of the window when user scrolls.

Scroll the page down and you'll see a box that follows your window scrolling, so that it is always visible.

How It Works

The moving block is just a HTML element, like this:

<div id="heart53100">♥♥♥♥♥ floating ♥♥♥♥♥ box ♥♥♥♥♥ something ♥♥♥♥♥</div>

The “id” attribute is there for JavaScript to identify it easily.

CSS is used to make it larger and red, and position it with respect to the HTML container (from top of the document). The important CSS code is this:

#heart53100 {position:absolute;
top:300px;
left:20px;
z-index:2;
height:6em;
width:10em;
font-size:1.5em;
color:red;
border:solid thin red
}

The position:absolute and “top” makes it offset 300 pixels down from top of the document. [see CSS Position: static, relative, fixed, absolute]

To move the widget, we need to:

  1. Set up a scroll event, so that when user scroll, a function ƒ is called.
  2. The function ƒ computes the distance of the widget to window's vertical center, and move the widget closer if it is not already there. (moving is done by changing its position in CSS.)
  3. The function ƒ then calls itself again, until the widget is in the center.

Each time ƒ moves the widget, the distance moved is proportional to how far it is to destination. So, if it is far, it moves a large distance, but if it is very close, it moves a small distance. This gives the illusion that the widget slows down like a train stop.

To make this efficient, ƒ will first turn off the scroll event when the widget is not at the center. When the widget is at the center, then ƒ turns back the scroll event. This make things more efficient, because otherwise each scroll will call ƒ while ƒ is still in the process of moving the widget to center.

Here's the JavaScript code:

// -*- coding: utf-8 -*-
// 2010-03-10, 2014-04-10
// change the position of a “div#heart53100” element.
// license: GNU GPL version 2.

(function () {

    var offsetFromTop = window.innerHeight/2; // number of pixels of the widget should be from top of the window
    var updateFrequency= 50; //milisecond. The smaller the value, smooth the animation.
    var chaseFactor = .05; // the closing-in factor. Smaller makes it smoother.

    var yMoveTo=0;
    var yDiff=0;

    var movingWidget = document.getElementById("heart53100");
    movingWidget.style.position="absolute";
    movingWidget.style.zIndex="2";
    movingWidget.style.top= offsetFromTop.toString() + "px";
    movingWidget.style.left="1ex";

    function ff(){
        // compute the distance user has scrolled the window
        yDiff = (navigator.appName === "Microsoft Internet Explorer") ? (yMoveTo - document.documentElement.scrollTop) : (yMoveTo - window.pageYOffset) ;

        if ( Math.abs(yDiff) > 9) {

            // turn off now, prevent the event repeatedly fired when user scroll repeatedly
            window.removeEventListener("scroll", ff);

            yMoveTo -= yDiff*chaseFactor;
            movingWidget.style.top  = (yMoveTo+offsetFromTop).toString() + "px" ;
            setTimeout(ff, updateFrequency); // calls itself again
        } else {
            window.addEventListener("scroll", ff , false); // turn back on
        }
    }

    window.addEventListener("scroll", ff , false);

})();

The code has this structure: (function () {…})();. This is a technique to wrap the whole code inside a function namespace and invoke the function, so we don't pollute the global namespace. JavaScript doesn't have namespace. [see JS: Functional Programing] [see JS: var Name Scope]

more height to play with
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|

Simple DOM Examples

  1. JS: Change CSS
  2. DOM: Change Element's Content
  3. DOM: Create HTML Element
  4. DOM: Remove HTML Element

  1. JS: document.write
  2. JS: Image Rollover
  3. JS: Pop-up New Window
  4. JS: Digital Clock
  5. JS: Stopwatch
  6. JS: Fade a Element
  7. JS: Fade a Element Using CSS Transition
  8. JavaScript UI: Shake Element
  9. JS: How to Create Tooltip
  10. JS: Falling Snow Effect
  11. JavaScript Floating Box Following Scroll
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon