0

I am trying this:

if($("#img").css("left")>=100)

but it always returns false because $("#img").css("left") returns "200px" as a string.

4 Answers 4

2

parseInt will convert the string into an integer for you:

if(parseInt($("#img").css("left"), 10)>=100)
Sign up to request clarification or add additional context in comments.

3 Comments

In case anyone was wondering, the second parameter is to define which numeral system to use, in that case base 10 numerals.
@MohamedKhamis Correct. Not sure that $("#img").css("left") would ever return prefixed numbers, but better safe than sorry :)
@RGraham better you add the explanation. Anyway I already +1 this
1

A temporary solution is to use this function that returns the value of the css attribute, excluding the "px":

function getCSSval(str){
    return parseInt(str.substring(0, str.length - 2));
    //e.g. "200px" --> "200"
}

But I was hoping there could be a more straight forward way

Comments

1

You need to parse the returned value to an integer to compare it with 100:

if (parseInt($("#img").css("left"), 10) >= 100)

Comments

1

The most efficient code to get the integer part is the use of regular expressions

if(parseInt($("#img").css("left").replace(/\s?px/i, "")) >= 100)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.