This question has already been answered:
I want to make it possible to move the block using the buttons, but for some reason the buttons do not work up and down, although everyone else works correctly, what could be the problem? All code attached below
var topPos = 0; var leftPos = 0; var top = document.getElementById("top"); var bottom = document.getElementById("bottom"); var left = document.getElementById("left"); var right = document.getElementById("right"); var moveBlock = document.getElementById("moveBlock"); function moveTop() { topPos -= 15; moveBlock.style.top = topPos + "px"; } function moveLeft() { topPos += 15; leftPos -= 15; moveBlock.style.left = leftPos + "px"; } function moveBottom() { topPos += 15; moveBlock.style.top = topPos + "px"; } function moveRight() { leftPos += 15; topPos += 15; moveBlock.style.left = leftPos + "px"; } left.onclick = moveLeft; right.onclick = moveRight; bottom.onclick = moveBottom; top.onclick = moveTop;
#top, #bottom, #right, #left { width: 100px; height: 30px; } .mainBlock { height: 500px; width: 1000px; background: #000; position: relative; margin: 0 auto; margin-top: 10px; } #moveBlock { height: 30px; width: 30px; top: 0px; left: 0px; background-color: green; position: absolute; border: 1px solid red; }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>test</title> <link rel="stylesheet" href="style.css"> </head> <body> <input id="top" type="button" value="TOP"> <input id="bottom" type="button" value="BOTTOM"> <input id="left" type="button" value="LEFT"> <input id="right" type="button" value="RIGHT"> <div class="mainBlock"> <div id="moveBlock"></div> </div> <script src="main.js"></script> </body> </html>