views:

74

answers:

2

Hey guys, I'm currently learning jQuery, and I am curious about something.

For functions that return sizes in strings, like say:

$(".some-class").css("line-height"); // => "18px"

Is there a way to compare them? For example, if I want to see if it's at least a certain size before doing something?

I'm not actually planning on using this, I'm just curious. I searched around but I didn't find anything. I imagine a plugin would have been written. Perhaps first making sure the comparative string is of the same units of measurement, then seeing which is the bigger number, or something like that.

As a side question, out of curiosity: in javascript, what would be the way to preserve only the number? So, how would I go about getting just 18 or "18" from "18px"? If, for fun/practice, I wanted to implement what I stated above, are there any methods I should take a look at, to split the number from the rest, or should I simply use regular expressions?

+2  A: 

I'm not too sure about the various forms of units, but to get the return value as an integer.

if (parseInt($(".some-class").css("line-height"), 10) < 18) {
    alert("It's less than 18px!");
}

Don't forget to set the radix of parseInt: http://www.w3schools.com/jsref/jsref_parseInt.asp

Matt
+1 for radix. `parseInt` is a common source of errors.
eyelidlessness
+1  A: 

Don't forget that if the line-height isn't set explicitly, the height returned will be "normal" (jsFiddle), so you should also handle that.... (normal is the default value, and it is supposed to be some sort of reasonable distance)

You can also use a regex to slice px off of the end. Once you get the string into that form, JS will do the type conversion for you (jsFiddle):

var height = $(".some-class").css("line-height");

if (height !== "normal") {

     // Remove 'px' from the end. The $ means the end of the line in a regex.
   height = height.replace(/px$/, ""); 

    if (height < 18) {
        alert("The height (" + height + ") is less than 18");
    } else {
        alert("The height (" + height + ") is greater or equal to 18");
    }
} else {
    alert("The height is " + height);
}

Here's a Stack Overflow question about line-height normal, and here is a rant about line-height normal by Eric Meyer.

Peter Ajtai