Suraj Prasad
Suraj Prasad

Reputation: 251

Set CSS attribute based on condition

I have a condition below which sets a CSS grid class based on the usecase length below:

jQuery(".uc"+useCases).addClass((landingPageData.description.useCases.length == 2) ?  'ibm-col-12-6' : 
 (landingPageData.description.useCases.length == 3) ? 'ibm-col-12-4' : 'ibm-col-12-3').attr('style','display:block');

Using the same method I want to add a width of % to a CSS class .ibm-columns based on the same above condition.

Below syntax is just a representation but I need the proper syntax

jQuery(".ibm-columns").css((landingPageData.description.useCases.length == 2) ? 'width: 60%;' : 
 (landingPageData.description.useCases.length == 3) ? 'width: 70%;' : 'width: 95%;');

Upvotes: 0

Views: 248

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337701

The issue is your syntax. css() accepts two arguments, the rule name and its value, yet you supply them both as a single string.

To fix this supply the values in an object:

jQuery(".ibm-columns").css((landingPageData.description.useCases.length == 2) ? 
   { 'width': '60%' } : 
   (landingPageData.description.useCases.length == 3) ? 
      { 'width': '70%' } : 
      { 'width': '95%' });

I would also suggest you break the ternary out to store the value in its own variable and supply that to css() to make the code more readable:

let width = landingPageData.description.useCases.length == 2 ? '60%' :
    landingPageData.description.useCases.length == 3 ? '70%' : '95%';

jQuery(".ibm-columns").css('width', width);

Upvotes: 2

Related Questions