Search code examples
javascripteventsmathpixel

Javascript - event.clientX & style.left - Mathematical Operations


I am stuck with a lil' problem over here. Let me explain:

document.getElementById(" ... ").style.left (horizontal position of object) will return a value like this: 100px or 1129px.

event.clientX (horizontal position of mouse-pointer) will return a value like this: 100or 1337.

I want to make math happen between these two. For example: var x = ( document.getElementById(" ... ").style.left ) + (event.clientX )

How can I do this, when one returns a value with pxand the other without? How can I get a regular number/px-number out of this? It does not seem to work to just add a (event.clientX) + "px" or document.getElementById(" ... ").style.left - "px"

Best regards! Comment if something is unclear I suppose!


Solution

  • Doing addition on strings will make Javascript try to concatenate them instead of doing actual math. Doing subtraction on strings that contain characters other than numbers will cause Javascript to fail in attempting to convert them to numbers and will give you NaN.

    You'll need to convert the string given to you by document.getElementById(" ... ").style.left to an integer using parseInt. parseInt will conveniently ignore non-numeric characters like those in 'px'.

    So, if w = document.getElementById(" ... ").style.left you could get the number in pixels by doing parseInt(w). You can do math with the value returned by parseInt because it will be an integer.