This is a function thats supposed to move an image slowly to the right, it isnt working... what did i mess up?
<script type="text/javascript">
var userWidth = window.screen.width;
function moveRight(id, speed) {
var pp = document.getElementById(id);
var right = parseInt(pp.style.left);
var tim = setTimeout("moveRight(id, speed)",50);
right = right+speed; // move
if (right > window.screen.height / 2)
{
right=0;
pp.style.left = right+"px";
}
}
</script>
Looks like id and speed aren't getting passed into moveRight(). When they're in the string as you have them they won't get evaluated. Have a look at this, it seems to do the trick. I stripped it down a little.
<div id="test" style="width: 50px; height: 50px; left: 0px; background-color: #000; position: absolute;"> </div>
<script type="text/javascript">
function moveRight(id, speed) {
var pp = document.getElementById(id);
var right = parseInt(pp.style.left) || 0;
right += speed; // move
pp.style.left = right + "px";
var move = setTimeout(function() {
moveRight(id, speed);
}, 50);
}
moveRight('test', 1);
</script>
A jsfiddle to play with. You can tweak it to your liking.
Related
Thanks to a really helpful user on this website (whose name I do not know, but I wish to thank and credit him!), I got the following tip on how to store area elements in an array so that when I mouse over a coordinate, I could display all of the overlay id's of the area elements that existed at that coordinate (even if the area elements were not at the same z-level):
I'm just stuck on one thing- once I have gathered all the elements that exist at the coordinate in the hoveredElements array, how do I show their overlay ids?
EDIT:
Here is an example of the full code (the overlay still does not display when I mouse over)
The file test.txt contains:
cscCSL1A15 700 359 905 318
cscCSL1A14 794 400 905 318
I use the maphilight plugin available online, and blanketaphi.png is the plot I use as a background.
<!DOCTYPE html>
<html>
<head>
<title>Detector Elements</title>
<script type="text/javascript"
src="Demo_imagemap_highlight_files/jquery-1.js"></script>
<!-- add maphilight plugin -->
<script type="text/javascript"
src="Demo_imagemap_highlight_files/jquery_002.js"></script>
</head>
<body>
<div class="content">
<div class="map"
style='display: block; background: transparent
url("Demo_imagemap_highlight_files/blanketaphi.png")
repeat scroll 0% 0%; position: relative; padding: 0px; width: 1037px;
height: 557px;'>
<canvas width="1037" height="557" style="width: 1037px; height: 557px;
position: absolute; left: 0px; top: 0px; padding: 0px; border: 0px none;
opacity: 1;"></canvas>
<img style="opacity: 0; position: absolute; left: 0px; top: 0px; padding: 0px;
border: 0px none;" src="Demo_imagemap_highlight_files/blanketaphi.png"
alt="foo" class="map maphilighted" usemap="#demo" height="557" width="1037"
border="0" />
</div>
</div>
<map name="demo" id="demo"></map>
</body>
</html>
<script type="text/javascript">
window.onload = function(){
var f = (function(){
var xhr = [];
var files = [ "test.txt"];
for (i = 0; i < 1; i++) {
(function (i){
xhr[i] = new XMLHttpRequest();
xhr[i].open("GET", files[i], true);
xhr[i].onreadystatechange = function () {
if (xhr[i].readyState == 4 && xhr[i].status == 200) {
// get text contents
j=20000*i + 50000;
var coords = xhr[i].responseText.split("\n");
coords = coords.filter(Boolean) //prevents extra rect with 0 coords
coords.forEach(function(coord) {
var area = document.createElement("area");
var att = document.createAttribute("data-maphilight");
if (i == 0) { //green
att.value = '{"strokeColor":"000000","strokeWidth":2,' +
'"fillColor":"009900","fillOpacity":0.5}';
}
area.setAttributeNode(att);
area.id = "r"+j;
area.shape = "rect";
area.coords = coord.substring(10,coord.length).trim()
.replace(/ +/g,","); // replaces spaces in txt file with commas
area.href = "#";
area.alt = "r"+j;
// create overlay with first term in string
var div = document.createElement("div");
div.id ="overlayr"+j;
div.innerHTML = coord.substring(0,10);
div.style.display = "none";
//increase j
j++;
// get map element
document.getElementById("demo").appendChild(area);
document.getElementById("demo").appendChild(div);
});
$('.map').maphilight();
//display overlay ids by mousing over
var elementPositions = [];
var hoveredElements = [];
if($('#demo')) {
$('#demo area').each(function() {
var offset = $(this).offset();
var top = offset.top;
var left = offset.left;
var bottom = $(window).height() - top - $(this).height();
var right = $(window).width() - left - $(this).width();
elementPositions.push({
element: $(this),
top: top,
bottom: bottom,
left: left,
right: right
});
//alert(top + "," + left + "," + right + "," + bottom);
});
$("body").mousemove(function(e) {
hoveredElements = [];
var yPosition = e.pageX;
var xPosition = e.pageY;
for (var i = 0; i < elementPositions.length; i++) {
if (xPosition >= elementPositions[i].left &&
xPosition <= elementPositions[i].right &&
yPosition >= elementPositions[i].top &&
yPosition <= elementPositions[i].bottom) {
// The mouse is within the element's boundaries
$("#hovers").append(elementPositions[i].element);
}
}
for (var i = 0; i < hoveredElements.length; i++) {
// The element as a jQuery object
var elem = hoveredElements[i];
var id = hoveredElements[i].attr('id');
$('#overlay'+id).show();
}
});
};
}
};
xhr[i].send();
})(i);
}
})();
};
</script>
Why not just something like this:
var elementPositions = [];
var hoveredElements = [];
if($('#demo')) {
$('#demo area').each(function() {
var offset = $(this).offset();
var top = offset.top;
var left = offset.left;
var bottom = $(window).height() - top - $(this).height();
var right = $(window).width() - left - $(this).width();
elementPositions.push({ element: $(this), top: top, bottom: bottom, left: left, right: right });
//alert(top + "," + left + "," + right + "," + bottom);
});
$("body").mousemove(function(e) {
hoveredElements = [];
var yPosition = e.pageX;
var xPosition = e.pageY;
for (var i = 0; i < elementPositions.length; i++) {
if (xPosition >= elementPositions[i].left &&
xPosition <= elementPositions[i].right &&
yPosition >= elementPositions[i].top &&
yPosition <= elementPositions[i].bottom) {
// The mouse is within the element's boundaries
hoveredElements.push(elementPositions[i].element);
$("#hovers").append(elementPositions[i].element);
}
} //end of for loop over all elements
console.log(hoveredElements);
for (var i = 0; hoveredElements.length; i++)
{ //for loop over all hovered elements
// The element as a jQuery object
var elem = hoveredElements[i];
var id = hoveredElements[i].attr('id');
console.log(id);
$('#overlay'+id).show();
// Do stuff to that jQuery element:
//??? something like elem.show();
}
You've got a lot of stuff here that doesn't make sense to me but here's what I can gather so far.
Your areas need to be in a container called demo area. Not sure how the space in the ID works so in my case I switched it to demoarea. Also somewhere in the page, there has to be another element called demo for anything to even happen.
Once that's done, the script loads demoarea into the elementPositions array. Judging from your description that's not what you want to do, you probably want to load all the elements inside demoareainto the array. So the first change is
$('#demo area').each(function() {
Becomes
$('#demoarea').children().each(function() {
Now what becomes confusing to me is that this script for whatever reason decides that you need to have another element called hover so it can move the element out of demoarea into hover when you mouse over it. If that is what you want, then you can do your show trick with some simple CSS.
<div style="display:none" id="overlayr6064"> Example Overlay ID name </div>
Becomes
<div id="overlayr6064"> Example Overlay ID name </div>
And then you add:
<style>
#demoarea div {
display: none;
}
#hover div {
display: block;
}
</style>
Assuming that is not what you wanted, what #liamEgan did to add the elements to the hoveredElements array is good, but you have an infinite loop here
for (var i = 0; hoveredElements.length; i++)
it should be
for (var i = 0; i < hoveredElements.length; i++)
Then the rest works... except one last thing, you want to load these listeners to your script when the page loads in a document ready method.
So in all it looks a bit like:
//display overlay ids by mousing over (my map is called 'demo')
var elementPositions = [];
var hoveredElements = [];
if($('#demo')) {
$('#demoarea').children().each(function() {
var offset = $(this).offset();
var top = offset.top;
var left = offset.left;
var bottom = $(window).height() - top - $(this).height();
var right = $(window).width() - left - $(this).width();
elementPositions.push({ element: $(this), top: top, bottom: bottom, left: left, right: right });
});
console.log('After Scanning demoarea elementPositions looks like:')
console.log(elementPositions);
$(document).ready(function () {
$("body").mousemove(function(e) {
hoveredElements = [];
var yPosition = e.pageX;
var xPosition = e.pageY;
for (var i = 0; i < elementPositions.length; i++) {
if (xPosition >= elementPositions[i].left &&
xPosition <= elementPositions[i].right &&
yPosition >= elementPositions[i].top &&
yPosition <= elementPositions[i].bottom) {
// The mouse is within the element's boundaries
if (typeof elementPositions[i].element != "undefined") {
hoveredElements.push(elementPositions[i].element);
$("#hovers").append(elementPositions[i].element);
}
}
} //end of for loop over all elements
for (var i = 0; i < hoveredElements.length; i++) { //for loop over all hovered elements
// The element as a jQuery object
console.log(hoveredElements[i]);
if (typeof hoveredElements[i] != "undefined") {
var elem = hoveredElements[i];
var id = elem.attr('id');
$('#overlay'+id).show();
}
// Do stuff to that jQuery element:
//??? something like elem.show();
}
});
});
}
#demoarea {
border: 2px blue dotted;
}
/* Border added so I can see where to mouse over */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="demo">
<div id="demoarea">
<area shape="rect" coords="431,499,458,491" href="#" id="r6064" alt="r6064">
<div style="display:none" id="overlayr6064"> Example Overlay ID name </div>
</div>
<div id="hovers">
</div>
</div>
Edit: sorry I added the undefined tests while fixing this because of the infinite loop but I think they're not really needed. Still nice to have though. Also since the area also gets moved into the hover area this script does try to show an element called overlayoverlayr6064r6064 which fortunately doesn't exist. But ya, again, probably not what you had in mind.
I have an animation which is called using onmousedown. I have another function which stops the animation (onmouseup).
The problem is that it only works the first time. By that I mean when I hold the button, it works and then stops when I stop pressing down but if I try to use either of the buttons after that first time nothing happens. It just won't move.
This is my HTML code (index.htm):
<html>
<head><link rel='stylesheet' href='style.css'></head>
<body>
<img id='player' src='img/player.png' style='height:64px;'></img>
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDownl (this)" onmouseup="OnButtonUpl (this)"><--</button>
<button id='moveright' onmousedown="OnButtonDownr (this)" onmouseup="OnButtonUpr (this)">--></button>
</div>
</body>
</html>
<script type='text/javascript' src='move.js'></script>
This is my javascript code (move.js):
var elem = document.getElementById("player");
function OnButtonDownl (button) {
var posl = document.getElementById("player").style.left;
window.idl = setInterval(framel, 5);
function framel() {
posl--;
elem.style.left = posl + 'px';
}}
function OnButtonUpl (button) {
clearInterval(idl);
}
var elem = document.getElementById("player");
function OnButtonDownr (button) {
var posr = document.getElementById("player").style.left;
window.idr = setInterval(framer, 5);
function framer() {
posr++;
elem.style.left = posr + 'px';
}}
function OnButtonUpr (button) {
clearInterval(idr);
}
Probably not important but here is my css (style.css):
body {
width: 100%;
height: 100%;
position:relative;
margin:0;
overflow:hidden;
}
#player {
position: absolute;
left:0;
bottom:0;
}
.buttons {
position:absolute;
right:0;
bottom:0;
}
Thanks for any help in advance.
You're running into 2 issues.
When you first get posl and posr, you're getting an empty string that JS is coercing to 0.
The -- and ++ won't work after you append the px (thus making posl and posr into string values)
Your posl-- (and posr++) can increment that coerced 0. That's why it works the first time through. The next time you mousedown the document.getElementById("player").style.left is a string — like "-1px" — that isn't interpreted as falsy (won't be coerced into 0). You can get around that by using parseInt() when you cache posl|posr but you have to provide a fallback of 0 because parseInt("") returns NaN…
You can work around that like so (with similar changes when you get posr):
var posl = parseInt( document.getElementById("player").style.left, 10 ) || 0;
var elem = document.getElementById("player");
function OnButtonDownl(button) {
//var posl = document.getElementById("player").style.left;
var posl = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idl = setInterval(framel, 5);
function framel() {
posl--;
elem.style.left = posl + 'px';
}
}
function OnButtonUpl(button) {
clearInterval(idl);
}
var elem = document.getElementById("player");
function OnButtonDownr(button) {
//var posr = document.getElementById("player").style.left;
var posr = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idr = setInterval(framer, 5);
function framer() {
posr++;
elem.style.left = posr + 'px';
}
}
function OnButtonUpr(button) {
clearInterval(idr);
}
body {
width: 100vw;// changed for example only
height: 100vh;// changed for example only
position: relative;
margin: 0;
overflow: hidden;
}
#player {
position: absolute;
left: 0;
bottom: 0;
}
.buttons {
position: absolute;
right: 0;
bottom: 0;
}
<img id='player' src='//placekitten.com/102/102' />
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDownl (this)" onmouseup="OnButtonUpl (this)">Left</button>
<button id='moveright' onmousedown="OnButtonDownr (this)" onmouseup="OnButtonUpr (this)">Right</button>
</div>
I was rewrite your code and it work (for me).
function Move(elem){
this.interval;
var posr = parseInt(getComputedStyle(document.getElementById("player")).left);
this.handleEvent = function(event) {
switch (event.type) {
case 'mousedown':
this.interval = setInterval(function() {
if (event.target.id == 'moveright') {
posr++;
} else if (event.target.id == 'moveleft'){
posr--;
}
document.getElementById("player").style.left = posr + 'px';
},5);
break;
case 'mouseup':
clearInterval(this.interval);
break;
}
}
elem.addEventListener('mousedown', this, false);
elem.addEventListener('mouseup', this, false);
}
var button_right = document.getElementById("moveright");
var button_left = document.getElementById("moveleft");
Move(button_right);
Move(button_left);
And in html you can remove js event listeners (this need only id).
First of all it is good practice to put your script tag inside your html tags:
<html>
<head>...</head>
<body>...</body>
<script type='text/javascript' src='move.js'></script>
</html>
Done that check this solution:
HTML:
<html>
<head><link rel='stylesheet' href='style.css'></head>
<body>
<img id='player' src='https://placeimg.com/54/45/any' style='height:64px;'></img>
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDown('left')" onmouseup="OnButtonUp()"><--</button>
<button id='moveright' onmousedown="OnButtonDown('right')" onmouseup="OnButtonUp()">--></button>
</div>
<script type='text/javascript' src='move.js'></script>
</body>
</html>
And js:
var nIntervId;
var b;
var elem = document.getElementById("player");
var posl = document.getElementById("player").style.left;
function OnButtonDown(button) {
b = button;
nIntervId = setInterval(frame, 5);
}
function frame() {
if(b==='left'){
posl--;
elem.style.left = posl + 'px';}
else{
posl++;
elem.style.left = posl + 'px';
}
}
function OnButtonUp() {
clearInterval(nIntervId);
}
http://output.jsbin.com/varaseheru/
Help! I've no idea what's going wrong here, I'm following along a tutorial video from Tuts+ The code is exact, yet the blue box is not animating to the left.
When I put an alert inside of the moveBox function, I see in the console the alert firing off the same message over and over again.
Here is my test link:
> Trying to animation a blue box left using Javascript <
Here is a screenshot from the video:
Here is my code:
(function() {
var speed = 10,
moveBox = function() {
var el = document.getElementById("box"),
i = 0,
left = el.offsetLeft,
moveBy = 3;
//console.log("moveBox executed " +(i+1)+ " times");
el.style.left = left + moveBy + "px";
if (left > 399) {
clearTimeout(timer);
}
};
var timer = setInterval(moveBox, speed);
}());
HTML:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>JavaScript 101 : Window Object</title>
<style>
#box {
position: abosolute;
height: 100px;
left: 50px;
top: 50px;
width: 100px;
background-color: Blue;
}
</style>
</head>
<body>
<div id="box"></div>
<script src="js/animation.js"></script>
You mispelled "absolute" in your positioning:
#box {
position: absolute; // Your mispelling here
height: 100px;
left: 50px;
top: 50px;
width: 100px;
background-color: Blue;
}
Once I fixed that, it worked fine.
A word of advice -- put a second condition in loops like this so that if the animation fails for some reason you don't end up in an infinite loop. For example, you might have done this:
(function() {
var maxTimes = 1000;
var loopTimes = 0;
var speed = 10,
moveBox = function() {
var el = document.getElementById("box"),
i = 0,
left = el.offsetLeft,
moveBy = 3;
//console.log("moveBox executed " +(i+1)+ " times");
el.style.left = left + moveBy + "px";
loopTimes += 1;
if (left > 399 || loopTimes > maxTimes) {
clearTimeout(timer);
}
};
var timer = setInterval(moveBox, speed);
}());
I want to slide or move a image from left to right something like in
http://rajeevkumarsingh.wix.com/pramtechnology
The read pentagonal box that moves Ok!
I tried a bit but failed to do so.
I used the code as below:
<script type="text/javascript">
<!--
var imgObj = null;
var animate ;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'absolute';
imgObj.style.top = '240px';
imgObj.style.left = '-300px';
imgObj.style.visibility='hidden';
moveRight();
}
function moveRight(){
if (parseInt(imgObj.style.left)<=10)
{
imgObj.style.left = parseInt(imgObj.style.left) + 5 + 'px';
imgObj.style.visibility='visible';
animate = setTimeout(moveRight,20); // call moveRight in 20msec
//stopanimate = setTimeout(moveRight,20);
}
else
stop();
f();
}
function stop(){
clearTimeout(animate);
}
window.onload =init;
//-->
</script>
<img id="myImage" src="xyz.gif" style="margin-left:170px;" />
There some kind of resolution problem with Firefox and IE as well. How to solve them. Also I am not able to move the things so clearly. Is this possible or not? I want it to be with JavaScript and not Flash.
var animate, left=0, imgObj=null;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'absolute';
imgObj.style.top = '240px';
imgObj.style.left = '-300px';
imgObj.style.visibility='hidden';
moveRight();
}
function moveRight(){
left = parseInt(imgObj.style.left, 10);
if (10 >= left) {
imgObj.style.left = (left + 5) + 'px';
imgObj.style.visibility='visible';
animate = setTimeout(function(){moveRight();},20); // call moveRight in 20msec
//stopanimate = setTimeout(moveRight,20);
} else {
stop();
}
//f();
}
function stop(){
clearTimeout(animate);
}
window.onload = function() {init();};
Here is an example of moving an image to the right as well as fading in from a .js file instead of your index page directly:
----------My index.html page----------
<!DOCTYPE html>
<html>
<body>
<script src="myJava.js"></script>
<script language="javascript" type="text/javascript">
//In pixels
var amountToMoveTotal = 1000;
var amountToMovePerStep = 10;
//In milliseconds
var timeToWaitBeforeNextIncrement = 20;
var amountToFadeTotal = 1.0;
var amountToFadePerStep = 0.01;
</script>
<p>This one moves right on hover</p>
<img onmouseover="moveRight(this, amountToMoveTotal, amountToMovePerStep, timeToWaitBeforeNextIncrement)" src="http://www.w3schools.com/jsref/smiley.gif" style="left:0px;top:50px;position:absolute;opacity:1.0;">
<br><br>
<p>This one fades in on hover</p>
<img onmouseover="fadeIn(this, amountToFadeTotal, amountToFadePerStep, timeToWaitBeforeNextIncrement)" src="http://www.w3schools.com/jsref/smiley.gif" style="left:0px;top:150px;position:absolute;opacity:0.1;">
</body>
</html>
----------My myJava.js code----------
var animate;
var original = null;
function moveRight(imgObj, amountToMoveTotal, amountToMovePerStep, timeToWaitBeforeNextIncrement)
{
//Copy original image location
if (original === null){
original = parseInt(imgObj.style.left);
}
//Check if the image has moved the distance requested
//If the image has not moved requested distance continue moving.
if (parseInt(imgObj.style.left) < amountToMoveTotal) {
imgObj.style.left = (parseInt(imgObj.style.left) + amountToMovePerStep) + 'px';
animate = setTimeout(function(){moveRight(imgObj, amountToMoveTotal, amountToMovePerStep, timeToWaitBeforeNextIncrement);},timeToWaitBeforeNextIncrement);
}else {
imgObj.style.left = original;
original = null;
clearTimeout(animate);
}
}
function fadeIn(imgObj, amountToFadeTotal, amountToFadePerStep, timeToWaitBeforeNextIncrement)
{
//Copy original opacity
if (original === null){
original = parseFloat(imgObj.style.opacity);
}
//Check if the image has faded the amount requested
//If the image has not faded requested amount continue fading.
if (parseFloat(imgObj.style.opacity) < amountToFadeTotal) {
imgObj.style.opacity = (parseFloat(imgObj.style.opacity) + amountToFadePerStep);
animate = setTimeout(function(){fadeIn(imgObj, amountToFadeTotal, amountToFadePerStep, timeToWaitBeforeNextIncrement);},timeToWaitBeforeNextIncrement);
}else {
imgObj.style.opacity = original;
original = null;
clearTimeout(animate);
}
}
Use the jQuery library, is really easy to do what you need
http://api.jquery.com/animate/
Follow sample code of page : http://api.jquery.com/stop/
<!DOCTYPE html>
<html>
<head>
<style>div {
position: absolute;
background-color: #abc;
left: 0px;
top:30px;
width: 60px;
height: 60px;
margin: 5px;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<button id="go">Go</button>
<button id="stop">STOP!</button>
<button id="back">Back</button>
<div class="block"></div>
<script>
/* Start animation */
$("#go").click(function(){
$(".block").animate({left: '+=100px'}, 2000);
});
/* Stop animation when button is clicked */
$("#stop").click(function(){
$(".block").stop();
});
/* Start animation in the opposite direction */
$("#back").click(function(){
$(".block").animate({left: '-=100px'}, 2000);
});
</script>
</body>
</html>
I have a JQuery function that makes a nav bar slide up or down as you scroll vertically. The idea is to always keep the navbar 20 pixels from the top of the client window. When the user scrolls up or down, the nav bar slides till it is back to 20 pixels from the top of the client window.
My Problem: It just wont bloody move lol. What have I done wrong?
Here is my JSFiddle with JQuery code: http://jsfiddle.net/wLga8/
Here is my code:
function moveDistanceEaseIn( /*HTML Element*/ ele, /*int|float*/ dist, /*Function*/ funct )
{
ele = $(ele);
var min = dist*0.01;
// kill an already running animation
if (ele.data("animInterval"))
clearInterval(ele.data("animInterval"));
var step = function()
{
if (dist <= min)
{
ele.data("animInterval", false);
clearInterval(interval);
return;
}
var stepMove = dist*0.1;
dist -= stepMove;
funct(ele, dist, stepMove);
};
var interval = setInterval(step, 30);
ele.data("animInterval", interval);
}
function moveToPointEaseIn( /*HTML Element*/ ele, /*int|float*/ curPoint, /*int|float*/ point, /*Function*/ funct, /*bool*/ signed )
{
ele = $(ele);
var dist = (signed == true) ? curPoint - point:Math.abs(curPoint - point);
moveDistanceEaseIn(ele, dist, funct);
}
$(document).ready(function()
{
$(window).scroll(function ()
{
var nav = $("#aa");
moveToPointEaseIn(nav, nav.position().top, $(window).scrollTop()+20, function(ele, dist, stepMove)
{
ele.css("top", ele.position().top+stepMove);
}, true);
});
});
And some example HTML:
<body style="height: 3000px;">
<div id="aa" style="position: absolute; left: 0px; top: 20px; width: 200px; height: 500px; background-color: red;"></div>
</body>
I'm not certain why your function isn't working. The fiddle wasn't set to use jquery, but even setting that has no effect.
However, this seems to do what you're after....
<body style="height: 3000px;">
<div id="aa" style="position: absolute; left: 0px; top: 20px; width: 200px; height: 500px; background-color: red;">
</div>
var $scrollingDiv = $("#aa");
$(window).scroll(function(){
$scrollingDiv.stop().animate({"marginTop": ($(window).scrollTop() + 0) + "px"}, 20 );
});
DEMO
Not sure if it will solve all of your problem, but these should at least get you up and running so you can debug your code further:
Add the jQuery library to your fiddle (missing in the one you posted)
The first time your step function runs, the values are negative: -100 and -1. This means your <= test will kill your animation on the first iteration
I hacked around this by changing this line:
if (dist <= min)
To this:
if (Math.abs(dist) <= Math.abs(min))
The animation still looks wrong, but at least it is animating :)
Here's the modified fiddle: http://jsfiddle.net/wLga8/4/