javascript – How do I toggle a div vertically using pure JS?

Question:

I managed to move horizontally using buttons(), and the onlcik method, however when I try to do the same but vertically using .style.bottom or .style.top and tried to change the increment but the position of my object doesn't change.

html :

<div id="caixa"> 
        <div id="caixinha">


        </div>
    </div>
    <br>
    <div>
        &emsp;&emsp;<button onclick = "MovUp()">↑</button>
        <br>
        <button onclick="movimentoDireita()"> ← </button>
        <button onclick="movBaixo">↓</button>
        <button onclick="movimentoEsquerdo()"> →</button>
    </div>

css :

#caixa{
            width: 200px;
            height: 200px;
            background: green;
            position: relative;   
        }
        #caixinha{
            width: 50px;
            height: 50px;
            background: red;
            position: absolute;
        }

js :

        var posH = 0
        var posL = 0
        var caixinhafilha = document.getElementById("caixinha")
        function MovUp(){
            if(posH<=0){

                caixinhafilha.style.top = posH + "px"

            }else{

                posH-- 
                caixinhafilha.style.top = posH + "px"
            }
        }
        function movBaixo(){
            if(posH>=150){

                caixinhafilha.style.bottom = posH + "px"

            }else{

                posH++
                caixinhafilha.style.bottom= posH + "px"
            }
        }

Answer:

Code problems:

  • The parentheses are missing when calling the function on onclick="movBaixo" .

  • In the movBaixo() function, the else should be style.top .

  • In the first if 's conditions, you can set the value to 0 .

var posH = 0
var posL = 0
var caixinhafilha = document.getElementById("caixinha")
function MovUp(){
   if(posH<=0){

       caixinhafilha.style.top = "0"

   }else{

       posH-- 
       caixinhafilha.style.top = posH + "px"
   }
}
function movBaixo(){
   if(posH>=150){

       caixinhafilha.style.bottom = "0"

   }else{

       posH++
       caixinhafilha.style.top= posH + "px"
   }
}
#caixa{
   width: 200px;
   height: 200px;
   background: green;
   position: relative;   
}
#caixinha{
   width: 50px;
   height: 50px;
   background: red;
   position: absolute;
}
<div id="caixa"> 
  <div id="caixinha">


  </div>
</div>
<br>
<div>
  &emsp;&emsp;<button onclick = "MovUp()">↑</button>
  <br>
  <button onclick="movimentoDireita()"> ← </button>
  <button onclick="movBaixo()">↓</button>
  <button onclick="movimentoEsquerdo()"> →</button>
</div>
Scroll to Top
AllEscort