JavaScript: Floating Box Following Scroll

By Xah Lee. Date: . Last updated: .
FLOATING BOX

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</div>

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

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

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

To move the box, we need to:

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

Each time f moves the box, 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 box slows down like a train stop.

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

Here's the JavaScript code:

// -*- coding: utf-8 -*-
// 2010-03-10, 2018-05-22
// Copyright 2018-05-22 by Xah Lee
// http://xahlee.info/js/moving_block.html
// license: permission is granted for using the code, but this license section must remain intact.

// box following scroll
// change position of β€œdiv#heart53100”

{

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

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

let yMoveTo=0;
let yDiff=0;

const moveIt = (() => {
    // distance user has scrolled
    yDiff = (yMoveTo - window.pageYOffset);

    if ( Math.abs(yDiff) > 9) {
        // turn off now, prevent event repeat firing when user kept scrolling
        window.removeEventListener("scroll", moveIt);

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

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

}
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|

Web Scripting Overview

  1. Browser Window Object, DOM
  2. Intro to Event-Based Programing
  3. JavaScript Load Order

DOM How-To

  1. Basic DOM Methods
  2. Get Element by ID, Tag, Name, Class, CSS
  3. Change CSS
  4. Change Node Content
  5. Create/Insert Node
  6. Remove Node
  7. Get Attribute Value
  8. Set Attribute Value
  9. Remove Attribute
  10. List/Add/Remove Class Attribute
  11. Add/Remove Event Handler
  12. Navigate DOM Tree
  13. Node Type, Name, Value

HTML Input

  1. Button
  2. Text Field
  3. Password Field
  4. Textarea
  5. Email πŸ“§
  6. Number Field
  7. Radio Button πŸ”˜
  8. Checkbox πŸ—Ή
  9. Popup Menu β–€
  10. Slider 🎚
  11. Color Picker 🌈

Web Scripting Examples

  1. Disable Right Click
  2. document.write
  3. Image Rollover
  4. Pop-up New Window
  5. Digital Clock
  6. Stopwatch
  7. Fade a Element
  8. How to Create Tooltip
  9. Falling Snow Effect
  10. Box Following Scroll

Web Scripting Misc

  1. Web Cookies
  2. Web Storage
  3. DOM: Open URL window.open
  4. Encode URL, Escape String
  5. Browser Info, Navigator Object
  6. Get URL (window.location)
  7. Find Window Width
  8. Find Element Width
  9. WebSocket
  10. Value of β€œthis” in Event Handler
  11. Event Delegation
  12. Get Current Script Tag
  13. insertAfter Element
  14. Randomize List
  15. create Document Fragment
  16. innerHTML, nodeValue, textContent, innerText?
  17. What is Live Object
  18. NodeList vs HTMLCollection
  19. Whitespace Nodes

jQuery

  1. jQuery Basics
  2. jQuery() vs querySelectorAll()
  3. Write JQuery Plugin

node.js

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. CSS
  3. JavaScript
  4. JS Obj Ref
  5. DOM
  6. SVG
  7. Blog