Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It puts strings together instead of adding them Javascript

Tags:

javascript

var x = e.pageX;
var myX = $(this).html();
var difference = myX - x;
var ex = myX + difference;

Everything workes until the last row. It doesn´t make an addition, it puts together the variables into one string. If myX is 10 and difference is 20 it will be 1020 when I want it to be 30.

How do I solve this?

like image 477
Daniel Avatar asked Aug 10 '11 14:08

Daniel


1 Answers

You can force the variables to be integer using something like this :

var ex = parseInt(myX, 10) + parseInt(difference, 10);

This happen because your variables are considered as strings, and using the + operator on strings concatenates then togheter instead of adding their numeric values.

like image 151
MaxiWheat Avatar answered Oct 30 '22 20:10

MaxiWheat