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".
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.
Use RegExp which replaces the 'px' by empty string and then convert the result to Integer using Number().
remove px from strings, add values, then add px back
(parseInt("40px".replace(/px/,""))+60)+"px"
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With