[Solved] JS numbers counter only works once [closed]


The click function is running each time but with the same reference to random. Random is evaluated once on the first execute of your script this is then used within your closure not re-evaluated. (literally tons of articles relating to closures to that you can read up on if you need to – here is one – http://javascriptissexy.com/understand-javascript-closures-with-ease/)

Bring the random inside your closure to ensure it evaluated on each click like so:

$('.punch1').on('click', (function(_this) {
      return function(e) {
          random = Math.ceil(Math.random() * 301232);
        return _this.countUp(random, '.right-counter span', 2222);
      };
    })(this));

http://jsfiddle.net/y6gwyv0x/1/

or make random a function which returns it’s value

random = function(){return Math.ceil(Math.random() * 301232);};
$('.punch1').on('click', (function(_this) {
  return function(e) {

    return _this.countUp(random(), '.right-counter span', 2222);
  };
})(this));

random still refers to the one outside the closure but because it is a function it will be run on each click returning a new number
http://jsfiddle.net/y6gwyv0x/3/

1

solved JS numbers counter only works once [closed]