I’m reading DOM Scripting and have a beginner question about the abstraction below. The original code didn’t include “clearTimeout”, and “movement” was declared as a global variable. While the code ran fine, it wasn’t a smooth animation which is why clearTimeout was added. My question however, is why I can’t just test for “movement” and when it fails (on the first mouseover call to moveElement) continue on through the rest of the function? If I keep “movement” as a global variable, rather than make it a property, the code doesn’t run at all?
If it helps to see the other JS and HTML, I’ve plugged the remaining code into jsFiddle.
function moveElement(elementID,final_x,final_y,interval) {
if (!document.getElementById) return false;
if (!document.getElementById(elementID)) return false;
var elem = document.getElementById(elementID);
if (elem.movement) { //Why can't I use "movement"?
clearTimeout(elem.movement);
}
var xpos = parseInt(elem.style.left);
var ypos = parseInt(elem.style.top);
if (xpos == final_x && ypos == final_y) {
return true;
}
if (xpos < final_x) {
xpos++;
}
if (xpos > final_x) {
xpos--;
}
if (ypos < final_y) {
ypos++;
}
if (ypos > final_y) {
ypos--;
}
elem.style.left = xpos + "px";
elem.style.top = ypos + "px";
var repeat = "moveElement('"+elementID+"',"+final_x+","+final_y+","+interval+")";
elem.movement = setTimeout(repeat,interval); //Originally global property
}
A property can never be
undefined, only have aundefinedas a value. In contrast, a variable may beundefined(not defined) or haveundefinedas a value.When you say
if (movement), in the case thatmovementis not defined, it will throw an exception.When you say
if (elem.movement), in teh case thatelem.movementis not defined, it will evaluate to false and fail the condition without exceptions.If you want to use
movementas a global variable, you must first declare it before attempting to read from it via:Alternatively, you could try to read the global
movementas a property, since all global variables are just properties of thewindowobject (in a browser):And finally, you could switch your if statement to one that protects itself against these exceptions via the
typeofoperator: