|
hey everyone...I'm pretty new at dHTML and Javascript in general...so perhaps I'm just doing something stupid here.
I've got a script in an external *.js file:
function moveImageDown(count, i){
if(i<10){
alert('I is ' + i);
document.myimage.style.position="relative";
document.myimage.style.top=(document.myimage.style.top+count);
i=(i+1);
}
else{
return 0;
}
moveImageDown(count, i);
} |
|
and I call to it from the HTML page as such:
<body onload="moveImageDown(10,0)">
<span class="bg1">
<img class="logo" id="myimage" src="..." alt="Text" />
</span> |
|
...of course, the image source is omitted for conciseness' sake. now, everything shows up fine, and the image is referenced properly from the javascript. In fact, it DOES move down the initial 10 pixels. However, on the first recursive call of the function, it gives me the Javascript alert message, but fails to move the image down (meaning it goes inside the loop alright, but for some reason isn't moving the element).
so, I'm thinking that there's either a problem with the reference to the element, in that once the function calls itself, it no longer has the same frame of reference...
either that, or (i'm hoping this is it), there's some problem with how I pass those same parameters into the function inside of the function. but that doesn't make much sense, since the 'i' variable works fine, so why wouldn't the 'count' var work? (and the 'i' does work, as my alerts keep popping up 1-9 as expected.
Any help would be much appreciated. Thanks!
|
|
|
Your problems may have to do with the fact that var+1 does not always assume that var is a number. Also, in Mozilla/Firefox, top and left will return the value with "px" after it. Like style.top = "150px";
Here is some code that works. "speed" is the number of milliseconds between each movement. 1000 = 1 second. Tweak as you need.
<html>
<head>
<script language="javascript">
function InitMove(ename, y, speed) {
if (y < 1) { return false; }
var e = document.getElementById(ename);
var top = ValidInteger(e.style.top);
//alert(top);
e.style.top = top/1 +1;
//alert("InitMove('"+ename+"',"+ (y/1-1) + "," + speed +");");
self.setTimeout("InitMove('"+ename+"',"+ (y/1-1) + "," + speed +");", speed);
}
function ValidInteger(wrkVar){
badChars = /[^0-9]/
if (badChars.test(wrkVar)) {
//alert("Value must be an integer only.");
}
wrkVar = wrkVar.replace(/[^0-9]/g,"");
if (!wrkVar) { wrkVar = 0 }
return wrkVar;
}
</script>
</head>
<body>
<a href="javascript:InitMove('foo',10,5)">Move</a>
<div id="foo" style="position:absolute;left:100;top:10;background-color:#ff0000;width:50px;height:50px;"> </div>
</body>
</html>
|
|
|
|
|
|
|
|
|
|
|
|