Xah Lee, 2006-01, 2010-10-23
This page shows you how to write a advanced 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 heart that follows your window scrolling, so that it is always in the vertical center of the window.
The moving block is just a HTML element, like this:
<div id="x0648e">♥</div>
The “id” attribute is there for javascript to identify it easily.
CSS is used to make it larger and red. The important ones is this:
position:absolute; z-index:2; top:50%;
If you are not familiar with these CSS attributes, see: CSS Position: static, relative, fixed, absolute, Examples.
The trick to get it move while user scrolls, is by changing the value of CSS's “top” attribute of this element.
In the javascript code, we do a loop of the script, at the rate of many times a second. Each time, the script finds out how much the window has been scrolled, then change the position of the element. This will position the block to the position we want. However, that does not give you the smooth following effect. The “following” effect is done by making the jump distance proportional to the scroll offset. So, if the page has large scroll offset, we move its position by big leaps. But if the offset is small, we move the block by a tiny distance. The closer the block is to the middle of the window, the smaller the steps it moves.
In summary, javascript changes the position of a HTML element. Each time moving the block closer to the desired position. Then, this function is called in a periodic loop.
Here's the javascript code:
// 2010-03-10, 2010-10-23 // change the position of a “div#x0648e” element. var posY=300; // verticle position from the top of the page var chasingFactor = .05; // the closing-in factor to desired position per update var updateFrequency=50; //milisecond var idleCheckFrequency=1 * 1000 ; //milisecond var yMoveTo=0; var ydiff=0; var g=document.getElementById("x0648e"); g.style.position="absolute"; g.style.zIndex="2"; g.style.top="50%"; g.style.left="1ex"; g.style.fontSize="7ex"; g.style.color="red"; function ff(){ // compute the distance user has scrolled the window if (navigator.appName == "Microsoft Internet Explorer") { ydiff = yMoveTo - document.documentElement.scrollTop; } else { ydiff = yMoveTo - window.pageYOffset; } if ( Math.abs(ydiff) > 9) { yMoveTo -= Math.round(ydiff*chasingFactor); g.style.top = (yMoveTo+posY).toString() + "px" ; setTimeout("ff()", updateFrequency); } else { setTimeout("ff()", idleCheckFrequency); } } window.onload = ff;
Once upon a time…
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
~FIN~
blog comments powered by Disqus