Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

how to move an image with arrow keys in javascript

//HTML document
<html>
  <head>
  <title>Moving image</title>
</head>
<body>
    <img id="movingImage" style="position:absolute;" src="https://image.freepik.com/free-vector/flat-design-red-comic-style-background_23-2148797742.jpg"/>
    </body>
</html>

//Javascript

//getting the image node
const movingImage = document.querySelector('#movingImage');

//when the user presses any key, the 'document.body.onkeydown' function is called
//move the image inside that function
document.body.onkeydown = (e) => {
  //handle the moving of image
  //e has a property called key which states the name of the key pressed
  
  switch(e.key){
    case 'ArrowUp':
      movingImage.offsetTop--;
      break;
      case 'ArrowLeft':
      movingImage.offsetLeft--;
      break;
      case 'ArrowRight':
      movingImage.offsetTop++;
      break;
      case 'ArrowDown':
      movingImage.offsetLeft++-;
      break;
  }
}
 
PREVIOUS NEXT
Tagged: #move #image #arrow #keys #javascript
ADD COMMENT
Topic
Name
6+8 =