Javascript counter for clicks

2

Suppose I have the following counter:

<button class="btn btn-primary" type="button">
    Curtir <span class="badge"> 4 </span>
</button>

I want to apply this code below:

function criaCounter(init) {
    var count = init || 0;
    return function() {
        count++;
        alert(count);
    }
}

$('#addCount').click(criaCounter(5));

so that it does not send an alert but increase the number next to the button to enjoy, always adding infinitely td time that someone clicks.

    
asked by anonymous 08.04.2016 / 17:02

2 answers

3

You can get the number with Node.textContent and add +1 to each click . Always replacing textContent .

var contador = document.querySelector('.badge');

document.querySelector('button').addEventListener('click', function(){
  var numero = parseInt(contador.textContent) + 1;
  contador.textContent = numero;
});
<button class="btn btn-primary" type="button">
  Curtir <span class="badge"> 4 </span>
</button>
    
08.04.2016 / 17:15
3

You can do this:

function criaCounter(init) {
    var count = init || 0;
    return function() {
       count++;
       var badges = document.getElementsByClassName("badge");
       for (var i in badges) {
          badges[i].innerHTML = count;
       }
   }
}

$('#addCount').click(criaCounter(5));
    
08.04.2016 / 17:14