I am still new to Javascript and JQuery. I have written a small function I run from document-ready. Its purpose is to set the height of a div as a multiple of line-heights:
function setLoginLinksHeight(numOfLines) {
var ll = hash(LOGIN_LINKS);
$(ll).css('line-height','130%');
var lh = $(ll).css('line-height');
var nh = lh * numOfLines; // Issue here
$(ll).height(nh);
}
From FireBug, the line-height I retrieve is 15.5833px. When I multiply it by 2 (for example), nh is set to NaN. I saw in this question that the retrieved value can have any format (%, px, etc…). This is scary!
How can I convert the returned value into a number of pixels without units into order to be able to create multiples of it? Is there a library/function available for this in Javascript or JQuery? What is the recommended practice in this case? Thanks.
EDIT
I have developed a small unit splitter following mblase75’s solution:
function splitUnit(e) {
var eUnit = '';
var eValue;
if( e && ( length = e.search( /px/ ) ) ) {
eUnit = 'px';
eValue = e.substr( 0, length );
} else if ( e && ( length = e.search( /em/ ) ) ) {
eUnit = 'em';
eValue = e.substr( 0, length );
} else {
eValue = e;
}
return new Array( eValue, eUnit );
}
Change to:
Of course, this doesn’t guarantee that you’ll be getting a number of pixels, just that you’ll be getting a number. To extract the units separately, add:
…and then combine the calculation with the old units: