Advertisement
metalx1000

Move Div Element HTML JavaScript Keypress

Mar 17th, 2020
797
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.   <head>
  4.     <title>JavaScript Key Press Move Div</title>
  5.     <meta charset="utf-8">
  6.     <meta name="viewport" content="width=device-width, initial-scale=1">
  7.     <style>
  8.       #sprite{
  9.         background:blue;
  10.         width:50px;
  11.         height:50px;
  12.         position: relative;
  13.         left: 10px;
  14.       }
  15.     </style>
  16.     <script>
  17.       //wait for document to load
  18.       document.addEventListener("DOMContentLoaded", function(){
  19.         let sprite = document.querySelector("#sprite");
  20.         sprite.pos = 0;
  21.         sprite.speed = 10;
  22.         sprite.mleft = false;
  23.         sprite.mright = false;
  24.       });
  25.  
  26.       document.addEventListener('keydown', function( ev ) {
  27.         if(ev.key == "ArrowRight"){ sprite.mright = true; }
  28.         if(ev.key == "ArrowLeft"){ sprite.mleft = true; }
  29.       });
  30.  
  31.       document.addEventListener('keyup', function( ev ) {
  32.         if(ev.key == "ArrowRight"){ sprite.mright = false; }
  33.         if(ev.key == "ArrowLeft"){ sprite.mleft = false; }
  34.       });
  35.  
  36.       //Main Game Loop
  37.       setInterval(function(){
  38.         if ( sprite.mleft ){ sprite.pos -= sprite.speed; }
  39.         if ( sprite.mright ){ sprite.pos += sprite.speed; }
  40.         sprite.style.left = sprite.pos + "px";
  41.       },10);
  42.     </script>
  43.   </head>
  44.   <body>
  45.     <div id="sprite"></div>
  46.   </body>
  47. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement