3

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...

Abdul Jabbar
  • 2,573
  • 5
  • 23
  • 43

3 Answers3

2

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

cssimsek
  • 1,255
  • 14
  • 20
2

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
}
mayabelle
  • 9,804
  • 9
  • 36
  • 59
1

Javascript is a language with implicit typing. That means you have to tell it what the types of things are when you want to do math. Your code just tells it to concatenate the strings, hence the result you are seeing.

Try this:

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