.toFixed()
returns a string (see the MDN documentation), that's why getPoints + addPoint
performs string concatenation, not addition.
Call that method after you performed the addition:
// unary + converts any numerical string to a number (no matter whether float
// or int)
var getPoints = +$('.awesome-points').text();
var newScore = getPoints + 1;
$('.awesome-points').text(newScore.toFixed(1));
Or more concise :
$('.awesome-points').text(function(i, val) {
return (+val + 1).toFixed(1);
});
How this works:
Instead of passing a value to .text()
, you can pass a function. This function will be executed for each of the selected elements. The first argument passed to the function is the index of the element in the set of selected elements and the second argument is the current text content. The return value will be set as new text content.
This is a good way to read and write the text content, without invoking .text()
twice.
(+val + 1).toFixed(1)
is evaluated as follows: First val
is converted to a number through the unary plus (+val
) and then increased by one (+ 1
). .toFixed(1)
is called on the result of that operation.
+val
will return NaN
if the text cannot successfully be converted into a number. I assume this won't happen in your case, but this can easily be dealt with with the expression
return ((+val || 0) + 1).toFixed(1);
That means, in case +val
evaluates to false
(which includes NaN
), we use 0
instead. It's a common pattern in JavaScript, see also What does "options = options || {}" mean in Javascript?.