-2

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!

mhuber
  • 11
  • 4
  • `start += 5.25;`? – Phiter Apr 17 '18 at 11:36
  • Thank you for your answer. But i would like to use multiple countups on the same page. – mhuber Apr 17 '18 at 11:41
  • The snippet can be invoked only one by one, it can't have multiple simultaneous calls. You need to change the function so, that it accepts arguments as parameters. Notice also, that we want to see the code here on the SO page, and your attempt as well. – Teemu Apr 17 '18 at 11:41

1 Answers1

0

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>
raul.vila
  • 1,984
  • 1
  • 11
  • 24
  • Awesome! Thank you. Possibly you also know how to add thousand separators between the number? – mhuber Apr 17 '18 at 11:51
  • Edit: sorry, I mixed JS and python (too much langague mixing for me today) --Here you have: [How to print number with commas as thousands separators?](https://stackoverflow.com/questions/1823058/how-to-print-number-with-commas-as-thousands-separators)-- – raul.vila Apr 17 '18 at 11:52
  • Sorry, I mixed JS and python, the JS version is [How to print a number with commas as thousands separators in JavaScript](https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript#2901298). Applying to the example: `$("#" + elemId).html(start[elemId].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));` – raul.vila Apr 17 '18 at 11:57
  • Works like a charm. Thank you! – mhuber Apr 17 '18 at 12:05