How to make a dot counter?

  • 0
    There is a counter that scrolls through only integers. Please tell me how to flip through numbers with a dot. For example 89.9.

    <h1><span class="count number" data-max="99.9">0</span>%</h1>


    var number = document.querySelector('.number'),
    		numberTop = number.getBoundingClientRect().top,
    		start = +number.innerHTML, end = +number.dataset.max;
    
    		window.addEventListener('scroll', function onScroll() {
    			if(window.pageYOffset > numberTop - window.innerHeight / 2) {
    				this.removeEventListener('scroll', onScroll);
    				var interval = setInterval(function() {
    					number.innerHTML = ++start;
    					if(start == end) {
    						clearInterval(interval);
    					}
    				}, 5);
    			}
    		});
    JavaScript Anonymous, Dec 28, 2019

  • 1 Answers
  • 0

    1. take the current value, multiply by 10

    2. increment / decrement (add / subtract one)

    3. divide by 10

    4. round to 1 decimal place, otherwise js is famous for its inaccuracy with float operations =)





    upd: like this to correct your script, but did not bother with rounding, if you see numbers in the form 86.500000003213 ... somewhere, then your homework for self-education is to round off before output =)

    <script type="text/javascript">
    var number = document.querySelector('.number'),
    numberTop = number.getBoundingClientRect().top,
    start = +number.innerHTML*10, end = +number.dataset.max*10; //правка раз

    window.addEventListener('scroll', function onScroll() {
    if(window.pageYOffset > numberTop - window.innerHeight / 2) {
    this.removeEventListener('scroll', onScroll);
    var interval = setInterval(function() {
    number.innerHTML = ++start/10; //правка два
    if(start == end) {
    clearInterval(interval);
    }
    }, 5);
    }
    });
    </script>
    William Rowe

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!