Question :
I was able to move horizontally using buttons (), and the onlcik method, however when I try to do the same however vertically using .style.bottom or .style.top and tried to change the increment however the position of my object does not change.
html:
<div id="caixa">
<div id="caixinha">
</div>
</div>
<br>
<div>
  <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 in
onclick="movBaixo"
. -
In function
movBaixo()
,else
should bestyle.top
. -
In the first condition of
if
‘s, you can set the value to0
.
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>
  <button onclick = "MovUp()">↑</button>
<br>
<button onclick="movimentoDireita()"> ← </button>
<button onclick="movBaixo()">↓</button>
<button onclick="movimentoEsquerdo()"> →</button>
</div>