Camilo Martin
Camilo Martin

Reputation: 37898

How to pass numerical values to jQuery's .css()?

I'm just starting with jQuery (and Javascript in general actually) and I feel the lack of strict typing is starting to bite me.

I need to pass values like '123px' or '#123' to jQuery's .css(), and it's not working if I generate the strings dynamically.

So string concatenation is done with +.

'123' + 'px' works.
123 + 'px' does not.
123.toString() + 'px' also does not!

Why? passing string + number concatenations elsewhere seems to work. Is this related to jQuery?
So, how can I create a string from a numerical value and a texual suffix/prefix for .css()?

Example: http://jsbin.com/ebiro4

Upvotes: 2

Views: 1011

Answers (3)

jAndy
jAndy

Reputation: 235992

'123' + 'px' works

123 + 'px' should also work, but do it like => '' + 123 + 'px'

123.toString() + 'px' should be => 123..toString() + 'px'

The last one is a little bit tricky. ECMA-/Javascripts expects full qualified decimal places in this spot. 123.0.toString() is pretty much the same as the .. shortcut.

#80 is never a numeric value in Javascript.

'#' + 080 does not work because 080 is an octal value. Firebug throws: 08 is not a legal ECMA-262 octal constant.

Upvotes: 3

user585756
user585756

Reputation:

Actually you need to use 123..toString() since Javascript is interpreting 123.toString() as a float value. The first thing you need to do is create a float with 123. which is equal to 123.0 and then convert it to a string.

Upvotes: 1

BoltClock
BoltClock

Reputation: 723588

Some CSS properties, like width() and height(), have dedicated jQuery methods that take numeric arguments and convert to px.

For others you should try and concatenate strings in order to avoid unexpected results. As an example, in your jsbin, you're trying to concatenate '#' and 080, which is actually 80 with an insignificant zero so you end up with '#80' which isn't a valid hex color code.

Upvotes: 2

Related Questions