JS: Floating Box Following Scroll
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="ft27872">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).
#ft27872 { 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 Propertyγ
To move the box, we need to:
- Set up a scroll event, so that when user scroll, a function f is called.
- 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.)
- 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 is the JavaScript code:
"use strict"; /* 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#ft27872β */ { 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 vMovingBox = document.getElementById("ft27872"); vMovingBox.style.position = "absolute"; vMovingBox.style.zIndex = "2"; vMovingBox.style.top = OffsetFromTop.toString() + "px"; vMovingBox.style.left = "8px"; let v_yMoveTo = 0; let v_yDiff = 0; const fMoveIt = (() => { // distance user has scrolled v_yDiff = (v_yMoveTo - window.pageYOffset); if (Math.abs(v_yDiff) > 9) { // turn off now, prevent event repeat firing when user kept scrolling window.removeEventListener("scroll", fMoveIt); v_yMoveTo -= v_yDiff * ChaseFactor; vMovingBox.style.top = (v_yMoveTo + OffsetFromTop).toString() + "px"; setTimeout(fMoveIt, UpdateFrequency); // calls itself again } else { window.addEventListener("scroll", fMoveIt, false); // turn back on } }); window.addEventListener("scroll", fMoveIt, false); }
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |