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

209
Views
I am making a counter in javascript. Can someone tell me how to 'loop' here so that the counter could increase everytime somone clicks the button

let count = document.querySelector(".count");

let dropBtn = document.querySelector(".btn-drop");

let resetBtn = document.querySelector(".btn-reset");

let addBtn = document.querySelector(".btn-add");

addBtn.addEventListener("click", function () {

let add = 0;

for (let i = 0; i ; i++) count.textContent = add += 1;

});

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I like closures for this. Your listener calls a function that sets up a default add variable, and returns a new function that acts as the function that's called when the button is clicked. This way you don't have any global variables. Basically closures are functions that carry the variables from their "outer lexical scope" when they get returned.

const count = document.querySelector('.count');
const addBtn = document.querySelector('.btn-add');

// Call a function that returns a new function that works
// as the click handler
addBtn.addEventListener('click', handleClick(), false);

// Initialise `add` with an initial default value
function handleClick(add = 0) {

  // Return a function that is called when the
  // button is clicked. That function (closure) will keep
  // a record of the `add` variable,
  // and update the content with its value when the button is clicked
  return function() {
    count.textContent = ++add;
  }

}
<div class="count">0</div>
<button class="btn-add">Update counter</button>

about 4 years ago · Juan Pablo Isaza Report

0

let addBtn = document.querySelector(".btn-add");

addBtn.addEventListener("click", function () {
  let count_element = document.querySelector(".count"); //select element with class "count"
  count = parseInt(count_element.innerText); //parse the text inside count_element to int
  count = count || 0; //if count Not a number, initial value of count is 0;
  count = count +1; //add 1 to counter
  count_element.innerText = count; //change count_element text to count
});
<button class="btn-add">ADD</button>
<div class="count">NaN</div>

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!