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

161
Views
How to update variable number inside of eventlistner with condinitional statement

Please excuse me as if this seems like a simple question. I want to update the sum every time the space bar key is pressed down along with updating the innerHTML. Whenever I press the spacebar it just concatenates my sum variable instead of simply adding it.

HTML

<div class="sec1 sec">
    <h1>Spacebar Challenge</h1>
</div>
<div class="sec2 sec">
    <p>
        You have hit the spacebar <span>0</span> times.
    </p>
    <div class='button'><button>Restart</button> </div>
</div>
<div class="sec3 sec"></div>
<script src="app.js"></script>

JS

let span = document.querySelector("span")

document.body.addEventListener("keyup", function (e) {
    let sum = 0
    if (e.code === "Space") {
        sum += 1
    }

    span.innerHTML += sum

})
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Try:

let span = document.querySelector("span")
let sum = 0

document.body.addEventListener("keyup", function(e) {
  if (e.code === "Space") {
    sum += 1
  }

  span.innerHTML = sum

})
<div class="sec1 sec">
  <h1>Spacebar Challenge</h1>
</div>
<div class="sec2 sec">
  <p>
    You have hit the spacebar <span>0</span> times.
  </p>
  <div class='button'><button>Restart</button> </div>
</div>
<div class="sec3 sec"></div>
<script src="app.js"></script>

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!