Let’s say that I want to invoke a function with the onClick method. Like this:
<li class="inline" onclick="mve(this);" >TEMP</li>
AND I have a JS function that looks like this:
function mve(caller){
caller.style.position = "relative";
caller.style.left = (caller.style.left+20) +'px';
var foo = setTimeout('mve(caller)', 2000);
}
My problem is that the element (which caller refers to) is undefined after the initial onClick call. At least this is what Firebug is telling me.
I’m sure it’s an easy solution, so how about just a simple explanation of why, and how?
Also if I run it like so:
function mve(caller){
caller.style.position = "relative";
caller.style.left = (caller.style.left+20) +'px';
}
I would think the element would move 20px right on every click, however that is not the case. Thoughts?
setTimeout()executes a string parameter in the global scope so your value ofthisis no longer present nor is your argumentcaller. This is one of many reasons NOT to use string parameters with setTimeout. Using an actual javascript function reference like this and it’s quite an easy problem to solve getting the arguments passed accordingly:For the second part of your question,
caller.style.leftis going to have units on it like20pxso when you add20to it, you get20px20and that’s not a value that the browser will understand so nothing happens. You will need to parse the actual number out of it, add 20 to the number, then add the units back on like this:Something that is missing from this function is a way for it to stop repeating. As you have it now, it goes on forever. I might suggest passing in either a number of iterations like this:
Also, you might be curious to know that this isn’t really a recursive function. That’s because the
mve()function callssetTimeout()and then finishes right away. It issetTimeout()that executes the next iteration ofmve()some time later and there is no accumulation on the stack frame of multiple function calls and thus no actual recursion. It does look like recursion from a glance at the code, but isn’t technically.