Created
September 16, 2019 09:41
-
-
Save codebubb/e9f4fce633c96cf3a91a694f3a93a547 to your computer and use it in GitHub Desktop.
how to move an object with arrow keys in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // <div id="block" style="position: absolute; top: 0; left: 0; width: 100px; height: 100px; background-color: red;"></div> | |
| <script> | |
| let modifier = 5; | |
| window.addEventListener('keydown', (event) => { | |
| const { style } = block; | |
| switch(event.key) { | |
| case 'ArrowUp': style.top = `${parseInt(style.top) - modifier}px`; break; | |
| case 'ArrowDown': style.top = `${parseInt(style.top) + modifier}px`; break; | |
| case 'ArrowLeft': style.left = `${parseInt(style.left) - modifier}px`; break; | |
| case 'ArrowRight': style.left = `${parseInt(style.left) + modifier}px`; break; | |
| } | |
| }); | |
| </script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment