3

I have like 40 foo's on the page, and each one is assigned a left/top value in another function.

$('.foo').css({
  top: isOn ? current_top_value_here : 500,
  left: isOn ? current_left_value_here : 500
});

so, I want to leave the top & left properties unmodified if isOn is true. How can I do that?

1
  • what is isOn? Javascript variable? Commented Jun 24, 2011 at 16:33

2 Answers 2

5

This way you can ensure they are only added if it's needed. Set up the object first with those values that you want assigned, and conditionally add some more. Then you can pass the object to your .css().

var cssProperties={
    'color' : 'yellow',
    ...
};

if (isOn) {
    cssProperties.top=500;
    cssProperties.left=500;
    /* alternative: $.extend(cssProperties, { 'top': 500, 'left': 500 }); */
}

$('.foo').css(cssProperties);
Sign up to request clarification or add additional context in comments.

1 Comment

In case I have misunderstood something, please show more of your code and explain what you need in a bit more detail. There might be good alternatives.
2

The best way would probably just be to not call it at all. If you have other css you're setting in the same statement, just split it apart:

if(!isOn){
  $('.foo').css({
    top: 500,
    left: 500
  });
}

$('.foo').css({
   // other stuff
});

4 Comments

but that means I have to duplicate my code, add like 20 lines+. I also have a animate function where I need to conditionally animate these properties too...
At least save the jQuery collection first, running $('.foo') twice is not a good practice.
@baz Yup, was just illustrating the idea, not optimizing it. Your idea is better anyway though, now that the question is further explained.
Meant no offense, just wanted to mention it in case somebody visits this question later for a code example to use :).

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.