ItsOdi ItsOdi - 7 days ago 7
CSS Question

Counting numbers up with animation

I want to count up a number with a animation. I have a HTML code where I set the number and a function which is counting this numbers. The problem is that I have a number

95%
with a percent character after it. But the function removes this character. Do you have any ideas why?



var fired = 0;
$(document).ready(function () {
if(fired === 0) {
$('.count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 3000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
fired = 1; //Only do scroll function once
}
});

.count {
font-size: 50px;
margin-bottom: 10px;
font-weight: 900;
text-transform: uppercase;
display: block;
padding-top: 15px;
}
#counter {
float: left;
display: block;
width: 28.71111111%;
text-align: center;
padding: 0 30px;
}
#counter h3 {
font-size: 1.2em;
font-weight: 100;
text-transform: uppercase;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="counter">
<h3>
<span class="count customer-satisfaction">95%</span>
Customer Satisfaction
</h3>
</div>




Answer

This is because the $(this).text(Math.ceil(now)) clears the <span class="count"> before inserting the number, if you tell the function to add the % to the number like so: $(this).text(Math.ceil(now) + '%'); it will be like you want it.

UPDATE from comment by OP

Turns out the case was that there were multiple <span class="count"> which stopped my original answer from working. By adding

if ($(this).hasClass('customer-satisfaction')) { 
    $(this).text(Math.ceil(now) + '%'); 
} else { 
    $(this).text(Math.ceil(now)); 
}

The % would only be added to the right number, instead of all.

var fired = 0;
$(document).ready(function () {
	if(fired === 0) {
		$('.count').each(function () {
			$(this).prop('Counter',0).animate({
				Counter: $(this).text()
			   	}, {
			   	    duration: 3000,
			      	easing: 'swing',
			    	step: function (now) {
			    	if ($(this).hasClass('customer-satisfaction')) { 
                        $(this).text(Math.ceil(now) + '%'); 
                    } else { 
                        $(this).text(Math.ceil(now)); 
                    }
			   	}
			});
		});
		fired = 1; //Only do scroll function once
	}
});
.count {
    font-size: 50px;
    margin-bottom: 10px;
    font-weight: 900;
    text-transform: uppercase;
    display: block;
    padding-top: 15px;
}
#counter {
    float: left;
    display: block;
    width: 28.71111111%;
    text-align: center;
    padding: 0 30px;
}
#counter h3 {
    font-size: 1.2em;
    font-weight: 100;
    text-transform: uppercase;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="counter">
	<h3>
		<span class="count customer-satisfaction">95%</span>
		Customer Satisfaction
	</h3>
</div>