If you want to achieve this using pure JavaScript:
HTML
<div id="floatingBox"></div>
CSS
#floatingBox {
position: fixed;
width: 100px;
height: 100px;
top: 30px;
right: 0;
border: 1px solid blue;
background-color: white;
}
JavaScript
window.onload = function() {
var body = document.getElementsByTagName('body')[0],
floatingBox = document.getElementById('floatingBox');
document.onscroll = function() {
floatingBox.style.top = 30 + Math.round(body.scrollTop / 10) + 'px';
};
};
Check out the live demo here: http://jsbin.com/qewujuhu/2/edit
Edit:
Explanation of How it Works
Your floating box is identified by an id
attribute in HTML. In CSS, its positioning is set to be fixed relative to the browser window and initial dimensions are specified. When the HTML document is fully loaded, the window.onload
function is triggered. Inside this function, the <body>
and <div id="floatingBox">
elements are located. A function is then defined to adjust the style
attribute of the <div id="floatingBox">
element based on the scrolling behavior of the document. This updating value will change the position of the box on the page dynamically.
The expression
floatingBox.style.top = 30 + Math.round(body.scrollTop / 10) + 'px';
calculates a new value for the
top
property of the
style
object within the element found by the
id
. It combines the initial offset with the current vertical scroll position divided by 10 (rounded to ensure whole numbers) and appends 'px' to indicate pixels. After scrolling down, the rendered result may look like this:
<div id="floatingBox" style="top:48px"></div>