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 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="id53100">♥</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:
div#id53100 { position:absolute; top:300px; left:1ex; z-index:2; }
The position:absolute and “top” makes it offset 300 pixels down from top of the document.
〔☛ CSS Position: static, relative, fixed, absolute〕
The trick to get it move while user scrolls, is first to set up a scroll event. So, our function fires only when user scrolls.
Then each time user scrolls, go thru a loop to change the position from top, making increasingly smaller change, until the difference of position is within a few pixels of the desired position. This “increasingly smaller change” makes the animation seems to slow down and arrive at destination.
Here's the JavaScript code:
// -*- coding: utf-8 -*- // 2010-03-10, 2010-10-23, 2013-04-27 // change the position of a “div#id53100” element. 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("id53100"); 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) { yMoveTo -= yDiff*chaseFactor; movingWidget.style.top = (yMoveTo+offsetFromTop).toString() + "px" ; setTimeout(ff, updateFrequency); // calls itself again } } // add even handler window.addEventListener("scroll", ff , false);
When user scrolls, our function “ff” is called.
ff then calculates the position it should move to. Instead of moving to it in one shot, it moves a fraction of the amount, then calls itself, then moves smaller fraction of amount.
more height to play with | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |blog comments powered by Disqus