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 tryi
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).
You can do this by parsing the css.left value of the object, somewhat like this:
$('#object2').css('left', (parseInt($('#object1').css('left')) + 60) + 'px');
But you should keep in mind, that the css.left value might not be px
but also %
, em
, etc. so the clean way would be using jQuery offset method as that would give you the correct pixels value.
$('#object2').css('left', ($('#object1').offset().left + 60) + 'px');
Probably the most efficient way is
parseInt("40px", 10) + parseInt("60px", 10) + "px"
The 10
's in the parseInt calls are necessary to protect against the value being mistakenly calculated in something other than base 10.
var shiftedRight = (parseFloat($('#object1').css('left')) + 60) + 'px';
$('#object2').css('left', shiftedRight);
parseFloat
will parse only the prefix of the string that is a number.
remove px from strings, add values, then add px back
(parseInt("40px".replace(/px/,""))+60)+"px"