Search
 
SCRIPT & CODE EXAMPLE
 

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;
  }
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: LazyLoad for images, Videos and Iframes JavaScript and JQuery 
Javascript :: initialize json array 
Javascript :: Statements and Expressions 
Javascript :: web3 check if contract 
Javascript :: identify unused node modules 
Javascript :: javascript removing items looping through array 
Javascript :: How i can use “LIKE” operator in mongoose 
Javascript :: div outside click event jquery 
Javascript :: sleep function javascript 
Javascript :: add mousedown event listener javascript 
Javascript :: javascript generate random hex 
Javascript :: js rectangle collision 
Javascript :: get time from a date time in jquery 
Javascript :: how to save data i mongi db 
Javascript :: how to repeat prompt with the same variable in javascript 
Javascript :: react native monorepo module resolver outside app 
Javascript :: subtract 18 years from today javascript 
Javascript :: an image gallery is a set of images with corresponding remove buttons 
Javascript :: react native textinput not show cursor 
Javascript :: check if a string is alphanumeric 
Javascript :: codewars playing with digits js 
Javascript :: == vs === 
Javascript :: js get website short name 
Javascript :: js throw error 
Javascript :: javascript get n random elements from array 
Javascript :: regex for ip address javascript 
Javascript :: email regular expression 
Javascript :: aws beanstalk nodejs redirect http to https 
Javascript :: open route in new tab vue router 
Javascript :: push elements to an object 
ADD CONTENT
Topic
Content
Source link
Name
1+9 =