Search code examples
javascriptfunctioncodepen

Javascript: Use countup-function multiple times


could anybody please help me.

I've found this nice countup-script: https://codepen.io/alemarengo/pen/mOWqwy

Now I would like to call this function multiple times for some other elements on the same site. But with different settings.

 start += 0.125;

Set addition from 0.125 to 5.25, for example.

Thank you in advance!


Solution

  • This is one possible approach: instantiate different go functions with different parameters:

    var start = {
      "counter-1": 7500000,
      "counter-2": 1500000
    };
    var speed = 1000;
    $(document).ready(function() {
      launch("counter-1", 1.5);
      launch("counter-2", 100)
    });
    
    function launch(elem, increment) {
      var go = goFactory(elem, increment)
      go();
      setInterval(go, speed);
    }
    
    function goFactory(elemId, increment) {
      function go() {
        $("#" + elemId).html(start[elemId].toFixed(0));
        start[elemId] += increment;
      }
    
      return go;
    }
    div {
      font-weight: normal;
      letter-spacing: 5px;
      padding: 6px;
      font-size: 1.8em;
      font-family: 'Gill Sans';
      width: 500px;
      text-align: center;
      height: auto;
      color: #333;
      display: block;
      margin: 0px auto;
      vertical-align: middle;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <html>
    
    <head>
      <title>Contatore</title>
    </head>
    
    <body>
      <div id="counter-1"></div>
      <div id="counter-2"></div>
    </body>
    
    </html>