Mohamed Khamis
Mohamed Khamis

Reputation: 8029

Conditional operators on css values using jQuery

I am trying this:

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

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

Upvotes: 0

Views: 46

Answers (4)

Linga
Linga

Reputation: 10563

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)

Upvotes: 1

Alexander Bondar
Alexander Bondar

Reputation: 534

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

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

Upvotes: 1

CodingIntrigue
CodingIntrigue

Reputation: 78545

parseInt will convert the string into an integer for you:

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

Upvotes: 2

Mohamed Khamis
Mohamed Khamis

Reputation: 8029

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

Upvotes: 1

Related Questions