Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally setting properties in jQuery.css()

Tags:

html

jquery

css

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?

like image 420
Alex Avatar asked May 30 '26 13:05

Alex


2 Answers

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);
like image 126
kapa Avatar answered Jun 01 '26 03:06

kapa


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
});
like image 27
James Montagne Avatar answered Jun 01 '26 03:06

James Montagne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!