0

How can we change propertyName/s with ternary operators?

For example:

var horizontal = false,
    propertyName = horizontal ? 'left' : 'top';

$(".elem").css({
    propertyName: value
});

I've found some answers, but they do not fit to my circumstances.

https://stackoverflow.com/a/5973518/1250044

https://stackoverflow.com/a/12228404/1250044


Praveen Kumar has found a possibility. But yet still no final!

OK, I think the best answer is, as Explosion Pills Explosion Pills said:

var horizontal = false;

$(".elem").css(horizontal ? {
    left: 10
} : {
    top: 10
});

Live as Fiddle.

1
  • true or false... any boolean! Commented Oct 12, 2012 at 6:22

2 Answers 2

4

You cannot evaluate a variable when declaring an object in literal notation.

Instead, you can directly give it this way:

elem.css((horizontal ? 'left' : 'top'), value);

Fiddle: http://jsfiddle.net/YXyng/

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

15 Comments

Smart. I don't need it today, but this will be used in the future for one or more of my projects.
That's clear, I've put the ternary operator in a variable for more clarity... By the way: This does not work yet! jsfiddle.net/73hcs
Wait. Am trying it out too. :( Same issue. It worked someway, but not now. Now am getting Uncaught SyntaxError: Unexpected token ILLEGAL. Will soon update the answer and fiddle. :)
Okat @yckart I will try some more, to get some working stuff. If not, then you have to work with how JSON is built!
@PraveenKumar I didn't mean to offend you. I just wanted to point out that Java Script Object Notation "per accident" looks like the Literal Notation used in javascript but has nothing to do with javascript (like JAVAscript has nothing to do with java). css() takes no JSON, it takes an (javascript)-object as parameter. In which notation this object is created doesn't matter. (Instead of the Literal Notation you can use a constructor or add properties directly via dot or bracket-notation)
|
1

You cannot directly hand over a variable value as identifier for an objectproperty but you can do the following:

var value = "15px";
var horizontal = true;
var propertyName = horizontal ? 'left' : 'top';
var parameters = {};
parameters[propertyName] = value;

elem.css(parameters);

See it live in this fiddle.

1 Comment

Good one! :) Way to go! Didn't think of this!

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.