Javascript function issue

I am trying to write a function that will move an element, adjusting its β€œleft” style over time. Currently, it does not work at all in its current 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 position of the element is no longer specified.

+4
source share
3 answers

Change the lines:

setTimeout(function moveOver( ), 100; 

to

 setTimeout(moveOver, 100); 

function moveOver( ) not a valid JavaScript syntax. Also, your brackets (or brackets) do not match. Since you have a syntax error, your code will not work.

For setTimeout you must pass the function as the first parameter, so mouseOver or function(){mouseOver();} will work.


Another problem of your script ... is that you will see that the element is constantly jumping.

You have two conditions: tabpos < 15.8 and tabpos > 15.8 . A condition whose fulfillment is not included in either of the two if blocks is tabpos == 15.8 ... but the JavaScript Number actually a floating point number. Due to the accuracy of the error, 15.8 == 15.7 + 0.1 will result in false , which shows that 15.8 not quite the same as 15.7 + 0.1 . Indeed, 15.7 + 0.1 approximately equal to 15.799999999999999 ...

Therefore, I suggest you use an integer value for tabPos , for example 158 , and divide it by 10 only when setting the style.


Possible result of your code:

 var tab; var tabPos; function init() { tab = document.getElementById("tab"); tabPos = 108; tab.style.left = tabPos / 10 + '%'; } function moveOver( ) { if (tabPos < 158) { setTimeout(moveOver, 100); tabPos = tabPos + 1; tab.style.left = tabPos / 10 + '%'; } else if (tabPos > 158) { setTimeout(moveOver, 100); tabPos = tabPos - 1; tab.style.left = tabPos / 10 + '%'; } } 
+1
source

The brackets for your setTimeout function calls are not closed:

 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 + '%'); // <---- } } 

You should see JavaScript errors reported by your browser.

+1
source

change setTimeout(function moveOver( ), 100; to setTimeout(moveOver, 100);

+1
source

All Articles