tags:

views:

708

answers:

7

I need to do a numeric calculation based on css properties.

However, when I use this to get info:

$(this).css('marginBottom')

it returns the value '10px'.

Is there a trick to just getting the number part of the value no matter whether it is px or % or em or whatever?

Thanks!

A: 
$(this).css('marginBottom').replace('px','')
Diodeus
That would handle only the 'px' case. So I guess a separate replace should be done for each of the remaining 'suffixes'.
Grzegorz Oledzki
+1  A: 
parseFloat($(this).css('marginBottom'),10)

Even if marginBottom defined in em, the value inside of parseInt above will be in px, as it calculated CSS property.

Alex Pavlov
A: 
parseInt($(this).css('marginBottom'));

parseInt will automatically ignore the units.

For example

var marginBottom = "10px";
marginBottom = parseInt(marginBottom);
alert(marginBottom); // alerts: 10
Bob
A: 

Should remove units while preserving decimals.

var regExp = new RegExp("[a-z][A-Z]","g");
parseFloat($(this).css("property").replace(regExp, ""));
Tyler
+4  A: 

This will clean up all non-digits and non-dots from the string:

$(this).css('marginBottom').replace(/[^\d\.]/g, '');
zakovyrya
+1  A: 

parseint will truncate any decimal values (e.g. 1.5em gives 1).

Try a replace function with regex e.g.

$this.css('marginBottom').replace(/([\d.]+)(px|pt|em|%)/,'$1');
pelms
A: 

// I use this:

$.fn.cssNum = function(){ return parseFloat($.fn.css.apply(this,arguments)); }

// Usage:

var e = $('.sel'); var nuwidth = e.cssNum('width')*10+'px'; e.css('width', nuwidth);

Quickredfox