tags:

views:

19

answers:

1
var gunboxwidth = ($('h2 span').widest().width() + "px" + 30 + "px") 

.widest() grabs the wides span inside of an h2, the problem i'm having is that it works fine when i DO NOT have

+ 30 + 'px'

why is that? is my syntax wrong?

A: 

Try:

var gunboxwidth = ($('h2 span').widest().width() + 30 + "px");

This adds 30 to the numerical value returned from the width function, then converts it to a string and adds the 'px' suffix.

For example, if the width of the span is '20', the JQuery width function will return the number 20 - not a string like '20px'. So the above code adds 30 to that and results in the string '50px'. What you have would result in a string value of:

'20px30px'

...since when you add strings together, the second is just appended to the first.

20 + 'px' = '20px'
'20px' + 30 = '20px30'
'20px30' + 'px' = '20px30px'


You're probably better off using:

var gunboxwidth = ($('h2 span').widest().width() + 30);

...to keep it numeric, and then using that to e.g. set the width of another item using JQuery's width function again, like:

$('.selector').width(gunboxwidth);
sje397