javascript move object with arrow keys

Solutions on MaxInterview for javascript move object with arrow keys by the best coders in the world

showing results for - "javascript move object with arrow keys"
Alyssia
16 Sep 2017
1// this can move an image
2
3//init object globally
4    var objImage = null;
5    function init() {
6        objImage = document.getElementById("image1");
7        objImage.style.position = "relative";
8        objImage.style.left = "0px";
9        objImage.style.top = "0px";
10    }
11    function getKeyAndMove(e) {
12        var key_code = e.which || e.keyCode;
13        switch (key_code) {
14            case 37: //left arrow key
15                moveLeft();
16                break;
17            case 38: //Up arrow key
18                moveUp();
19                break;
20            case 39: //right arrow key
21                moveRight();
22                break;
23            case 40: //down arrow key
24                moveDown();
25                break;
26        }
27    }
28    function moveLeft() {
29        objImage.style.left = parseInt(objImage.style.left) - 5 + "px";
30    }
31    function moveUp() {
32        objImage.style.top = parseInt(objImage.style.top) - 5 + "px";
33    }
34    function moveRight() {
35        objImage.style.left = parseInt(objImage.style.left) + 5 + "px";
36    }
37    function moveDown() {
38        objImage.style.top = parseInt(objImage.style.top) + 5 + "px";
39    }
40    window.onload = init;