I have two number tickers on my page and both tickers are merging into one.
Demo:
$(document).ready(function() {
var initialValue = $('#ticker .count').text()
$('#ticker').waypoint({
handler: function() {
$('.count').each(function() {
const format = formatter(initialValue)
$(this).prop('Counter', 0).animate({
Counter: format.value
}, {
duration: 1500,
easing: 'swing',
step: function(now) {
$(this).text(format.revert(Math.ceil(now)));
}
});
});
},
offset: '100%'
});
})
// keep string after count
function formatter(str) {
const char = 'x'
const template = str.replace(/\d/g, char)
const value = str.replace(/\D/g, '')
function revert(val) {
const valStr = val.toString()
let result = ''
let index = 0
for (let i = 0; i < template.length; i++) {
const holder = template[i]
if (holder === char) {
result += valStr.slice(index, index + 1)
index++
} else {
result += holder
}
}
return result
}
return {
template: template,
value: value,
revert: revert
}
}
.gap {
background: lightgrey;
height: 20px;
}
.gap2 {
margin: 20px 0px;
background: red;
height: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js"></script>
<div id="ticker">
<span class="count counter">16,000+</span>
</div>
<div class="gap"></div>
<div id="ticker">
<span class="count counter">$64 million</span>
</div>
<div class="gap2">Expected output below (but they obviously count up to that number)</div>
<!-- expected output -->
<div id="ticker">
<span>16,000+</span>
</div>
<div class="gap"></div>
<div id="ticker">
<span>$64 million</span>
</div>
Why is this happening? I believe the issue to be in this line:
const format = formatter(initialValue)
Because when commented out, although it doesn't count up, it only displays one number. But can't see why this is causing this merge?
Edit:
Have edited snippet to showcase expected end result.