user1563944
user1563944

Reputation: 403

Targeting CSS Properties Through If/Else Statement

Ok, hopefully this is a pretty straight forward question. As the title suggests, is it possible to target the opacity property when using it in an if else statement? If it is how would you go about writing the code?

Could you do something like this, or am I way off?

if ($("#someObject").css().opacity == 1) {
    // do this
} else if {$("#someObject").css().opacity == 0){
    // do this instead
};

Upvotes: 1

Views: 2594

Answers (2)

Oriol
Oriol

Reputation: 288620

Based on Robin's answer, you could use switch:

switch($("#someObject").css('opacity')){
  case 1:
    // do this
    break;
  case 0:
    // do this instead
    break;
}

Upvotes: 0

Robin Whittleton
Robin Whittleton

Reputation: 6339

If you’re using jQuery (and it looks like you are) then you’re almost there:

if ($("#someObject").css('opacity') == 1) {
  // do this
} else if ($("#someObject").css('opacity') == 0){
  // do this instead
};

would be the correct code.

To be more specific about what this is doing, the .css() method in jQuery when used with a single parameter is an accessor for the computed CSS on an element - pass in a CSS rule and you’ll get the set value back.

If I was going to make any change it’d be to cache the value first so that you don’t make a possible multiple selection / evaluation call. E.g.

var setOpacity = $("#someObject").css('opacity');
if (setOpacity == 1) {
  // do this
} else if (setOpacity == 0){
  // do this instead
};

Upvotes: 3

Related Questions