Give movement to buttons using javascript

0

I have the following code in which I try to give a movement animation to several buttons and that gives me an error:

//variables de la animación
var button0 = document.getElementById("button0");
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
var button3 = document.getElementById("button3");

var pos0 = 0;
var pos1 = 0;
var pos2 = 0;
var pos3 = 0;

var direction0 = "down";
var direction1 = "down";
var direction2 = "down";
var direction3 = "down";

//proceso
function animateButton(button, pos, direction) {
    if (pos == 20) {
        direction = "up";
    } else if (pos == 0) {
        direction = "down";
    }

    if (direction == "down") {
        button.setAttribute("style", "top:" + pos + "px");
        pos++;
    } else if (direction == "up") {
        button.setAttribute("style", "top:" + pos + "px");
        pos--;
    }
}

setInterval( function() { animateButton(button0, pos0, direction0); }, 90 );
setInterval( function() { animateButton(button1, pos1, direction1); }, 90 );
setInterval( function() { animateButton(button2, pos2, direction2); }, 90 );
setInterval( function() { animateButton(button3, pos3, direction3); }, 90 );

What can you owe?

    
asked by psy 13.10.2017 в 20:23
source

1 answer

0

You say that if pos == 20 then direction = up , and then below if direction == up then do something else, the same as if pos == 0 , direction = down , and if direction = down something else ...

Do not you think it's shorter and the same logic, if you say this?

if (pos == 0) {
        button.setAttribute("style", "top:" + pos + "px");
        pos++;
    } else if (pos == 20) {
        button.setAttribute("style", "top:" + pos + "px");
        pos--;
    }

Also, do not believe 4 setInterval , with one you are enough, anyway they are for the same time and if it were not like that, then if you would have to create more for other times, it would be:

Example:

setInterval(function(){

animateButton(button0, pos0, direction0);
animateButton(button1, pos1, direction1);
animateButton(button2, pos2, direction2);
animateButton(button3, pos3, direction3);
},90)

Those things look at them, the less code, the less you have to analyze.

Edit your question with the description of the mistakes you have to understand better.

I suggest you study the scope of this in javascript, understanding that you will find your error, study also the .call() .apply .bind() functions.

    
answered by 13.10.2017 / 21:04
source