{"id":1521,"date":"2019-04-13T13:20:01","date_gmt":"2019-04-13T05:20:01","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=1521"},"modified":"2020-05-12T10:36:52","modified_gmt":"2020-05-12T02:36:52","slug":"how-to-detect-keyboard-presses-made-to-the-browser-screen-with-javascript","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-detect-keyboard-presses-made-to-the-browser-screen-with-javascript\/","title":{"rendered":"How to detect keyboard presses made to the browser screen with JavaScript"},"content":{"rendered":"<p>When you are building a browser-based game, being able to track key presses is helpful. <\/p>\n<p>For this purpose, you can register a JavaScript function that gets called when the browser detects a key is being pressed.<\/p>\n<p>After the browser detects a key press, it will send information about the key to your function.<\/p>\n<p>When your function is able to get the key that is pressed, it can then use this information to update the game state.<\/p>\n<p>In this post, let's look at how we can detect keyboard presses made to the browser screen with JavaScript.<\/p>\n<h2>Basic JavaScript codes to detect keyboard presses made to entire browser screen<\/h2>\n<p>First, let us look at the basic JavaScript codes that will detect keyboard presses made to the browser screen:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\ndocument.addEventListener(&quot;keydown&quot;, onKeyPressed);\r\n\r\nfunction onKeyPressed(e) {\r\n    var keyCode = e.keyCode;\r\n    var key = e.key;\r\n    console.log('Key Code: ' + keyCode + ' Key: ' + key);\r\n}\r\n<\/pre>\n<p>As shown above, we first use the <code>addEventListener()<\/code> of the <code>document<\/code> object to register the <code>onKeyPressed<\/code> function to the <strong>\"keydown\"<\/strong> event. Given that, the <code>onKeyPressed<\/code> function will be called every time the user presses a key when the browser is active. In addition to that, the browser will provide an Event Object that provides information about the key that was pressed.<\/p>\n<p>After the <code>onKeyPressed<\/code> function is called, we assign the key code and key from the Event object to the <code>keyCode<\/code> and <code>key<\/code> variables. Once we have the key code and key, we then used the <code>console.log<\/code> function to print them to the browser console.<\/p>\n<h3>Sample output from running the JavaScript codes<\/h3>\n<p>When we type the sentence: <strong>\"The quick brown fox jumps over the lazy dog.\"<\/strong>, we should get the following output in the browser console:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\r\nKey Code: 16 Key: Shift\r\nKey Code: 84 Key: T\r\nKey Code: 72 Key: h\r\nKey Code: 69 Key: e\r\nKey Code: 32 Key:  \r\nKey Code: 81 Key: q\r\nKey Code: 85 Key: u\r\nKey Code: 73 Key: i\r\nKey Code: 67 Key: c\r\nKey Code: 75 Key: k\r\nKey Code: 32 Key:  \r\nKey Code: 66 Key: b\r\nKey Code: 82 Key: r\r\nKey Code: 79 Key: o\r\nKey Code: 87 Key: w\r\nKey Code: 78 Key: n\r\nKey Code: 32 Key:  \r\nKey Code: 70 Key: f\r\nKey Code: 79 Key: o\r\nKey Code: 88 Key: x\r\nKey Code: 32 Key:  \r\nKey Code: 74 Key: j\r\nKey Code: 85 Key: u\r\nKey Code: 77 Key: m\r\nKey Code: 80 Key: p\r\nKey Code: 83 Key: s\r\nKey Code: 32 Key:  \r\nKey Code: 79 Key: o\r\nKey Code: 86 Key: v\r\nKey Code: 69 Key: e\r\nKey Code: 82 Key: r\r\nKey Code: 32 Key:  \r\nKey Code: 84 Key: t\r\nKey Code: 72 Key: h\r\nKey Code: 69 Key: e\r\nKey Code: 32 Key:  \r\nKey Code: 76 Key: l\r\nKey Code: 65 Key: a\r\nKey Code: 90 Key: z\r\nKey Code: 89 Key: y\r\nKey Code: 32 Key:  \r\nKey Code: 68 Key: d\r\nKey Code: 79 Key: o\r\nKey Code: 71 Key: g\r\nKey Code: 190 Key: .\r\n<\/pre>\n<p>As shown above, the key code is an integer while the key is either a character or word depending on the key that is pressed.<\/p>\n<h2>Getting the barcode from a barcode scanner with JavaScript<\/h2>\n<p>Since most <a href=\"https:\/\/www.amazon.com\/s\/ref=as_li_ss_tl?k=usb+barcode+scanners&ref=nb_sb_noss&linkCode=ll2&tag=clivsperswebs-20&linkId=5dfeab67f0d23ec7c19616e0e6beea3d&language=en_US\" rel=\"noopener\" target=\"_blank\">barcode scanners<\/a> act like a keyboard, it is possible to get barcode with JavaScript.<\/p>\n<p>When I ran the earlier JavaScript codes with my browser and scanned a barcode with my barcode scanner, I realised that:<\/p>\n<ul>\n<li>A capital letter results in two key presses. For example if there is an A in the barcode, key presses are made to Shift and A.<\/li>\n<li>At the end of the barcode, there is a newline character.<\/li>\n<\/ul>\n<p>Given these points, we can get the barcode from a barcode scanner with JavaScript codes similar to the following:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\ndocument.addEventListener(&quot;keydown&quot;, onKeyPressed, false);\r\n\r\nvar barcode = '';\r\n\r\nfunction onKeyPressed(e) {\r\n  var keyCode = e.keyCode;\r\n  if(keyCode == 13) {\r\n    alert(barcode);\r\n    barcode='';\r\n  } else {\r\n    if (keyCode != 16) {\r\n      barcode = barcode + e.key;\r\n    }\r\n  }\r\n}\r\n<\/pre>\n<p>In addition to the basic JavaScript codes discussed earlier, we now add a barcode variable outside of the <code>onKeyPressed<\/code> function. <\/p>\n<p>When we detect a newline character (key code: 13), we use the <code>alert<\/code> function to show the barcode. After the alert, we reset the barcode to an empty string.<\/p>\n<p>When a key is not a newline character and not a Shift (key code: 16), we add the key to the <code>barcode<\/code> variable.<\/p>\n<p>Given these points, we will be able to get a barcode from the barcode scanner in JavaScript. When we want to verify the barcode, we can then replace the alert function with an <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-send-http-post-requests-and-http-get-requests-using-jquery\/\" rel=\"noopener\" target=\"_blank\">Ajax call to a server endpoint<\/a>.<\/p>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-ox\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-ox&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-ox&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F1521&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>When you are building a browser-based game, being able to track key presses is helpful. <\/p>\n<p>For this purpose, you can register a JavaScript function that gets called when the browser detects a key is being pressed.<\/p>\n<p>After the browser detects a key press, it will send information about the key to your function.<\/p>\n<p>When your function is able to get the key that is pressed, it can then use this information to update the game state.<\/p>\n<p>In this post, let&#8217;s look at how we can detect keyboard presses made to the browser screen with JavaScript.<\/p>\n","protected":false},"author":1,"featured_media":1213,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[620,624,621,209,623,16,128,622],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/JavaScript-Logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-ox","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/1521"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=1521"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/1521\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1213"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=1521"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=1521"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=1521"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}