In this video, we will use JavaScript to move a circle through a webpage with left, right, up and down keys from keyboard.
Source Code :
<style> body{ background: #2bc198; } .circle{ border-radius: 50%; background: #1f3fdc; width: 100px; height: 100px; position: absolute; } </style> <div class="circle"></div> <script type="text/javascript"> var circle = document.getElementsByClassName('circle')[0]; document.onkeydown = checkKey; var move_by = 50; function upPress(){ var top = circle.offsetTop; new_top = top - move_by; circle.style.top = new_top + 'px'; } function downPress(){ var top = circle.offsetTop; new_top = top + move_by; circle.style.top = new_top + 'px'; } function leftPress(){ var left = circle.offsetLeft; new_left = left - move_by; circle.style.left = new_left + 'px'; } function rightPress(){ var left = circle.offsetLeft; new_left = left + move_by; circle.style.left = new_left + 'px'; } function checkKey(e){ e = e || window.event; if(e.keyCode == '38'){ upPress(); } else if(e.keyCode == '40'){ downPress(); } else if(e.keyCode == '37'){ leftPress(); } else if(e.keyCode == '39'){ rightPress(); } } </script>