-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
2
  • Welcome to SO. Please take a tour of the help centre to see how to ask a good question. Links to codepen must be accompanied by code in the question itself - see how to create a minimal reproducible example
    – Pete
    Commented Aug 9, 2018 at 12:04
  • Just move you prevent default inside your if: 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
    Commented Aug 9, 2018 at 12:30

1 Answer 1

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"; 
  }
});
2
  • 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 so your second point is totally wrong
    – Pete
    Commented Aug 9, 2018 at 12:23
  • @Pete is right! Filip, you should put the "e.preventDefault" inside your if.
    – Hoch
    Commented Aug 10, 2018 at 13:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.