0

I can't figure out what I'm doing wrong here.

So I want to use jquery to check if a css class's property value is equal to something. If it is, then execute some code and if not execute some other code.

The issue is that some of it will work and others will not. For example here is my jquery:

if (jQuery( ".mobile_swap" ).css('height') == '100%' ){
        console.log("worked");
    } else {
        console.log("nope");
    }

Now it does not work but if I change it to this:

if (jQuery( ".mobile_swap" ).css('height') == '100px' ){
        console.log("worked");
    } else {
        console.log("nope");
    }

it will work. So my question is why does it recognize the px's but not the percentages? It also will not work with auto. Obviously, when I test for this I'm making sure that the css part is correct so it would be true.

Thanks in advance!

3
  • 100% != 100px in most cases Commented Jan 14, 2014 at 19:17
  • Check what kind of value you get from that height... console.log() Commented Jan 14, 2014 at 19:18
  • This might be helpful: Can jQuery Return Height of an Element as a Percentage Commented Jan 14, 2014 at 19:20

2 Answers 2

5

jQuery evaluates the current inner height, in pixels, of the selected DOM element (in your case ".mobile_swap"). This is never a percentage.

Percentages can only be used when defining CSS styles, after which the browser evaluates the percentage and sets the element to that height (in px) on page load.

If you absolutely needed to evaluate it based on percentage, you'd need to retrieve the parent element's height (or width) and perform some basic calculations based on the height (or width) of the child element.

Sign up to request clarification or add additional context in comments.

Comments

1

If only one element with this specific class, use:

jQuery( ".mobile_swap" ).height() === jQuery( ".mobile_swap" ).parent().height()

Otherwise, you will have to iterate through all elements using each loop and compare own height with parent height. 100% meaning parent height.

1 Comment

Thanks @A.Wolff I got the height of the parent and used that in the if then statement.

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.