javascript - Change img source when key is pressed and back when released -


what want accomplish: when user presses spacebar image source should change spacebar.png spacebar_pressed.png. when user releases key image should change default.

i have looked around everywhere , tried several possibilities none worked. bear in mind i'm not javascript.

html:

    <!doctype html> <html lang="sv">     <head>     <meta charset="utf-8">     <title></title>     <link rel="stylesheet" href="css/stylesheet.css">     <script src="js/jquery-3.2.1.min.js"></script>     <script src="js/spacebar.js"></script> </head> <body>     <h1>spacebar simulator 2017</h1>     <img src="assets/spacebar.png" id="spacebar"> </body> </html> 

this recent code have tried:

$("#spacebar").on("keydown", function(e){     var code = e.keycode;     if(code == 32){      document.getelementbyid("spacebar").src="../assets/spacebar_pressed.png";     } }); 

you can combine keypress , attr function accomplish such task.

in callback, have event object, attribute which keycode, represents key pressed. keycode 32 spacebar.

when key gets released on dom, url changes again explicitly.

$(function() {    var myrealurl = "http://hammerjs.github.io/assets/img/stackoverflow-icon.svg";    $("body").on("keydown", function(e) {      if (e.which == 32) {        $("#spacebar").attr("src", "https://i.stack.imgur.com/ce5lz.png");        console.log('pressed');      }    });      $("body").keyup(function(e) {      if (e.which == 32) {        $("#spacebar").attr("src", myrealurl);        console.log('released');      }    });  });
/*demo use*/  img {    max-height: 100px;    max-width: 100px;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <img src="http://hammerjs.github.io/assets/img/stackoverflow-icon.svg" id="spacebar" />


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -