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

3
  • 1
    Look at the parseInt function in JavaScript. Commented Dec 10, 2013 at 16:54
  • stackoverflow.com/questions/1133770/… Commented Dec 10, 2013 at 16:54
  • 1
    .value returns a string. See the linked duplicate for how to convert it to an integer Commented Dec 10, 2013 at 16:55

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

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 } 

Comments

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 } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.