Home > Software engineering >  I am making a counter in javascript. Can someone tell me how to 'loop' here so that the co
I am making a counter in javascript. Can someone tell me how to 'loop' here so that the co

Time:03-05

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;

});

CodePudding user response:

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 >0</div>
<button >Button</button>

CodePudding user response:

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 >ADD</button>
<div >NaN</div>

  • Related