I am trying to write a function that will move an element by adjusting its ‘left’ style over time. Its currently not working at all in its present form.
var tab;
var tabPos;
function init() {
tab = document.getElementById("tab");
tabPos = 10.8;
tab.style.left = tabPos + '%';
}
function moveOver( ) {
if (tabPos < 15.8)
{
setTimeout(function moveOver( ), 100;
tabPos = tabPos + 0.1;
tab.style.left = tabPos + '%';
}
else if (tabPos > 15.8)
{
setTimeout(function moveOver( ), 100;
tabPos = tabPos - 0.1;
tab.style.left = tabPos + '%';
}
}
The init function successfully sets the initial position of the element but I added the moveOver function to the code the element’s position is no longer set.
Change the lines:
to
function moveOver( )isn’t a valid JavaScript syntax. Also, your brackets (or parenthesis) doesn’t match. Because you have a syntax error, your code will not work.For
setTimeout, you are supposed to pass a function as the first parameter, somouseOverorfunction(){mouseOver();}will work.Another problem of your script… is that you will see the element constantly jumping.
You have two conditions:
tabpos < 15.8andtabpos > 15.8. The condition which execution doesn’t enter either one of both if-blocks istabpos == 15.8… but JavaScript’sNumberis actually a floating point number. Thanks to precision error,15.8 == 15.7 + 0.1will result infalse, which shows that15.8is not exactly the same as15.7 + 0.1. In fact,15.7 + 0.1is approximately equal to15.799999999999999…So I suggest you to use an integer value for
tabPos, for example158, and divide it by10only when setting the style.A possible result of your code: