Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add javascript pixel values?

Is there a way in javascript/jQuery to take two variables with values "60px" and "40px" and add them together to get "100px"?

Or in a more general sense, I'm trying to calculate positions of objects relative to other objects and it would be really convenient if I could do something like this:

$('#object2').css('left', $('#object1').css('left')+'60px');

Of course, that just gives in invalid "40px60px".

like image 483
joshuahedlund Avatar asked Feb 17 '12 17:02

joshuahedlund


People also ask

What is PX JavaScript?

Px. js is a JavaScript library for extracting and manipulating data stored in PC-Axis files. It is intended as a generic solution which can handle any well-formed PC-Axis file. Px. js is primarily intended for use in a web browser but it can also be used as a Node.

How do you convert pixels to integers?

Use RegExp which replaces the 'px' by empty string and then convert the result to Integer using Number().


2 Answers

remove px from strings, add values, then add px back

  (parseInt("40px".replace(/px/,""))+60)+"px"
like image 62
Roman Goyenko Avatar answered Oct 03 '22 04:10

Roman Goyenko


You're looking for the parseInt() function.

var left1 = "40px";
var left2 = "60px";

// Add the integer values of the left values together
var leftTotal = parseInt( left1, 10 ) + parseInt( left2, 10 ) + "px";

Also worth investigating is the parseFloat() method. It does the same thing as parseInt(), but works on numbers with decimals (aka floating point values).

like image 22
Daniel Szabo Avatar answered Oct 03 '22 04:10

Daniel Szabo