Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integers adding as strings in Javascript [duplicate]

I have two text fields imageWidth and imageHeight... i want to take input from them, add current mouse poointer position and then do some stuff:

x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
var wWidth = document.getElementById('imageWidth').value;  
var wHeight = document.getElementById('imageHeight').value;
var b = x + wWidth;
alert(b);
if(x+wWidth < 800 && y+wHeight < 1560)
{
//some work here
}

so if user enters 400 in width are and x returns 151... b's value will be 151400... whereas i want it to be 551 for the loop to work properly...

like image 481
Abdul Jabbar Avatar asked Feb 14 '26 10:02

Abdul Jabbar


2 Answers

You should read up on the parseInt() method --> parseInt() on MDN

like image 103
cssimsek Avatar answered Feb 15 '26 23:02

cssimsek


This should work:

x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
var wWidth = document.getElementById('imageWidth').value;  
var wHeight = document.getElementById('imageHeight').value;
var x1 = parseInt(x, 10) + parseInt(wWidth, 10);
var y1 = parseInt(y, 10) + parseInt(wHeight, 10);
if(x1 < 800 && y1 < 1560)
{
    //some work here
}
like image 31
mayabelle Avatar answered Feb 16 '26 00:02

mayabelle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!