2

In such a code:

var a = e.clientX;
var b = document.getElementById('someElement').style.left;
var z = a - b;

the output is NaN. Viewing the outputs separatly i see, that a is only numbers whereas b is numbers ending with 'px'. Setting it var a = e.clientX + 'px'; still doesnt work.

Thanks


I thank you for your suggestions, but the best outcome is 0 with the Number() method (from the other methods the outcome is NaN). . . any ideas?

2
  • Subtracting a number and a string is gonna give you bad results, and subtracting two strings is no better. Tried something like parseInt(b) ?
    – user1499731
    Oct 7, 2015 at 18:56
  • 1
    should consider floating numbers, parseFloat is a better option
    – Alan
    Oct 7, 2015 at 19:54

4 Answers 4

1

The value of style.left should be a string. While you can add numbers to string via JavaScript's automatic type conversion, subtracting a number from a string will always result in NaN.

You need to first convert the string to a number. Here are two ways you can do that.

var b = Number(document.getElementById('someElement').style.left);

var b = parseInt(document.getElementById('someElement').style.left);
1
var a = parseInt(e.clientX, 10);
var b = parseInt(document.getElementById('someElement').style.left, 10);
var z = (a - b) + 'px';
1

Try

b = parseFloat(document.getElementById('someElement').style.left)
0
0

Both the values need to be Number before doing subtract operation. The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

var a = e.clientX;
var b = document.getElementById('someElement').style.left;
var z = a - parseInt(b);
alert(z);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.