0

I'm trying to get an alert to appear if two conditions are met:

  • The value of the display property on the #playerbox element is block, AND
  • The value of the display property on the #playerinfo element is none

I have this:

if ($("#playerbox").css("display") == "block" && $("#playerinfo").css("display") == "none"){
    alert("test");
}

But the alert never appears. However, testing just one element will work:

if ($("#playerbox").css("display") == "block"){
    alert("test");
}

So I'm assuming I'm not chaining the two selectors together correctly in the if statement. What am I doing wrong?


UPDATE: I should have specified that #playerinfo is inside #playerbox. Does that change anything?

3
  • Have you also separately tested: $("#playerinfo").css("display") == 'none'? Commented Feb 22, 2012 at 21:10
  • Oops, misread the question. Answer deleted. Commented Feb 22, 2012 at 21:11
  • Your code seems to work on its own: jsfiddle.net/s3Ze9 (click anywhere to test). Maybe you should alert or console.log the values before the if statement runs to see if you are getting what you expect? Commented Feb 22, 2012 at 21:13

3 Answers 3

5

Why not use :visible and :hidden?

if ($("#playerbox:visible,#playerinfo:hidden").length == 2){
     ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

It works, but so does the OP's code: jsfiddle.net/s3Ze9 (click anywhere to test)
Turns out the problem was with something else in my script, but Ori's code is cleaner and shorter than mine anyway. I'll take it anyway :-)
3

Are you sure you JQuery actually found the elements you are looking for?

alert($("#playerbox").length);

alert($("#playerinfo").length);

if either of those are coming back as 0, then you aren't really getting those elements. Maybe you are have a typo, or the class name set rather than the id.

1 Comment

Good answer. If no element is selected then .css() will return undefined, for example: $('#doesnt-exist').css('display') will return undefined. And undefined == "none" will always resolve to false.
0

Use is

For example

 if($("#playerinfo").is(":hidden")) /* :visible for your other selector */
       //do stuff

1 Comment

It works, but so does the OP's code: jsfiddle.net/s3Ze9 (click anywhere to test)

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.