Js fiddle
JS:
(function() { var button = document.getElementsByClassName("button"); var circle = document.getElementById("circle"); var down = 0, up = 0, left = 0, right = 0; for (var i = 0; i < button.length; i++) { button[i].addEventListener('click', function(e) { var position = e.currentTarget.value; // for bottom and top, use marginTop, but for one increase by 5 // and for the other decrease by 5 if (position === "down") { down += 5; circle.style.marginTop = down + "px"; } if (position == "up") { up -= 5; circle.style.marginTop = up + 'px'; } // same thing for left and right, use marginLeft, but for one increase by 5 // and for the other decrease by 5 if (position == "left") { left -= 5; circle.style.marginLeft = left + 'px'; } if (position == "right") { left += 5; circle.style.marginLeft = left + 'px'; } }) } }());
UPDATE
Alternatively, you can move top and left and values ββinstead of marginTop and marginLeft as follows:
JS Fiddle 2
(function() { var button = document.getElementsByClassName("button"); var circle = document.getElementById("circle"); var posTop = circle.offsetTop, posLeft = circle.offsetLeft; for (var i = 0; i < button.length; i++) { button[i].addEventListener('click', function(e) { var position = e.currentTarget.value; if (position === "down") { posTop += 5; circle.style.top = posTop + "px"; } if (position == "up") { posTop -= 5; circle.style.top = posTop + 'px'; } if (position == "left") { posLeft -= 5; circle.style.left = posLeft + 'px'; } if (position == "right") { posLeft += 5; circle.style.left = posLeft + 'px'; } }) } }());
source share