Counter Javascript de clicks

Asked

Viewed 5,296 times

3

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 increases the number next to the like button, always adding infinitely td once someone clicks.

  • There is only one <span class="badge"> 4 </span> on the page?

  • True, well remembered. are various on the page, each new post a 0 zeroed counter with the like button begins. to weigh in using that of the same faceboo.

  • Okay, if there are several you need to take that into account. I’ll give you an answer too, but I still don’t know what the '#addCount'... can you explain the idea? is to show the count?

2 answers

6

You can take the number with Node.textContent and add +1 to each click. Always replacing the 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>

  • 1

    I think it’s worth explaining that in this answer you’re suggesting a different approach where you don’t use AP code.

3

You can do it like 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));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.