Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
JS - Why isnt the second value in my "or" equation recognised

im trying to create a function that will move an png image either up, down, left or right by the user either pressing WASD or the Arrow Keys. At the moment i have figured out a way to move the item using WASD however when i introduce the "or" operand and use the Key.Code for the arrow keys the arrow keys aren't recognised even though it will still recognise WASD

<body>
<div class="scene">
  <div class="rocket">
    <img src="rocket.png" alt="" />
  </div>
</div>
<script src="script.js"></script>
    document.addEventListener("keydown", (e) => {
    var rocket = document.querySelector(".rocket");
    let speed = 10;

     if (event.keyCode == (87 || 38) && rocket.offsetTop > 100) {
     rocket.style.top = `${rocket.offsetTop - speed}px`;
     }
     if (event.key == "s" && rocket.offsetTop < window.innerHeight - 300) {
     rocket.style.top = `${rocket.offsetTop + speed}px`;
     }
     if (event.key == "a" && rocket.offsetLeft > 50) {
     rocket.style.left = `${rocket.offsetLeft - speed}px`;
     }
     if (event.key == "d" && rocket.offsetLeft < window.innerWidth - 125) {
     rocket.style.left = `${rocket.offsetLeft + speed}px`;
     }
     if (event.key == " " && rocket.offsetTop > 100) {
     rocket.style.top = `${rocket.offsetTop - 200}px`;
     }
     console.log(event.keyCode);
     });
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

This expression:

87 || 38

Evaluates to 87. Every time. Which means this expression:

event.keyCode == (87 || 38)

Compares the value to 87. Every time.

Don't think of these logical conditions as intuitive human language. They need to be built as individual logical expressions which individually evaluate to a value. What you're looking for is this:

(event.keyCode == 87 || event.keyCode == 38)
about 4 years ago · Juan Pablo Isaza Relatório

0

You should try

 if ((event.keyCode == 87 || event.keyCode == 38)  && rocket.offsetTop > 100)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda