Reputation: 97
I want to add 20px to the width of a property that is autogenerated. I found this post but I can't seem to find the appropriate solution for my problem. Javascript (+) sign concatenates instead of giving sum of variables
this is my code:
settings.autowidth ? $(self).width() : settings.width;
settings.autowidth = true, so this will return $(self).width() which is 151px.
When I want to add 20 px like this, I get 15120px
settings.autowidth ? $(self).width()+'20px' : settings.width;
The solution in the above mentioned link says I need to add some brackets, But I don't know where to place them.
Upvotes: 2
Views: 101
Reputation: 25413
You could use a little utility function:
function addPx( orig, val ) {
var noSuffix = orig.split('px')[0];
return (Number(noSuffix)+val) + "px";
}
alert(addPx("30px", 10)); // 40px
alert(addPx("0px", 20)); // 20px
Upvotes: 0
Reputation: 7301
No need for the px
.
When you added the px
and the quote '
you are saying add the text '20px'
of the width in this case 150 so you end up with the effect of adding two strings.
To have the values treeted as numbers remove the quotes '
and the px
.
settings.autowidth ? $(self).width() + 20 : settings.width;
Upvotes: 3
Reputation: 700612
The value of $(self).width()
is not the string "151px"
, it's the number 151
.
Just add 20
to the number:
settings.autowidth ? $(self).width() + 20 : settings.width;
If you want it in the format "171px"
then you add the px
to it:
settings.autowidth ? ($(self).width() + 20) + 'px' : settings.width;
Upvotes: 1
Reputation:
You're trying to count a string with a number.
Basically you're doing this:
"string" + 150
Which would result in "string150"
;
Correct way of doing this is:
settings.autowidth ? $(self).width() + 20 : settings.width;
Upvotes: 1