Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda