-4

in the past week I worked on a game with my teacher - rEAndom game (http://reandomgame.clanweb.eu/ it is in Czech, so use the built-in google translate please :). It's a javascript, jQuery and HTML5 game. The thing I wanted to talk about is a feature in which you press TAB and the div with the score appears. I have this code on CodePen: https://filipt.cf/2OSHcS9

I have two major problems with this:

  1. when I press Tab and release it, the div doesn't disappear.
  2. even though I prevented the default behavior of the Tab key, it does weird stuff on the page
Filip
  • 345
  • 2
  • 12
  • Welcome to SO. Please take a tour of the [help centre](http://stackoverflow.com/help) to see [how to ask a good question](http://stackoverflow.com/help/how-to-ask). Links to codepen must be accompanied by code in the question itself - see how to create a [mcve] – Pete Aug 09 '18 at 12:04
  • Just move you prevent default inside your if: https://codepen.io/anon/pen/wxQLJr and remove the mouse events - they don't cause button codes so they would never fire the hide and show so not sure why you would attach them – Pete Aug 09 '18 at 12:30

1 Answers1

0

You have two errors.

First: You should use "e.preventDefault();" inside of each function.

Second: As far as i remember, the "on" function get only one event.

This code works to me:

$(document).on('keydown', function(e) {
  if(e.which == 9) {
        e.preventDefault();
        document.getElementById("hs").style.display = "block";
  }
});

$(document).on('keyup', function(e) {
  if(e.which == 9) { 
        e.preventDefault();
        document.getElementById("hs").style.display = "none"; 
  }
});
Hoch
  • 43
  • 1
  • 6
  • 1
    you are preventing all button presses in your document - if you decide to add inputs at a later date, they will not work and you can [bind multiple events with on](https://stackoverflow.com/questions/2534089/jquery-multiple-events-to-trigger-the-same-function) so your second point is totally wrong – Pete Aug 09 '18 at 12:23
  • @Pete is right! Filip, you should put the "e.preventDefault" inside your if. – Hoch Aug 10 '18 at 13:10