2

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.

4 Answers 4

3

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Indeed, I probably have tried all possibilities except this one... (I thought I have tested this as well though) Thanks for the quick answer!
@KevinRovers If you mark the answer as the accepted answer, green tick on the left, then it will help other users in future, you also get a small bit of rep +2 for accepting answers :)
1

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;

Comments

1

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;

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.