Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!