-3
\$\begingroup\$

In my javascript code I have as below,

    ($('.field-name-field-sponsorship-image').length > 0) ? (evoJustIn.css('margin-top', '-260px')) : (evoJustIn.css('margin-top', '-300px'));

Yes, I am using jQuery. Why is ESLint complaining? I am guessing this is not a good practice to write ternary operator like this? What is wrong with this and how to make it better? It work.. just can't seem to understand the reasons behind ESLINT complaining...

\$\endgroup\$
2
  • \$\begingroup\$ Your question lacks the necessary context for a good review. See How to Ask. Your goal is to conditionally set a CSS margin; that should be the title of the question. Also, I strongly recommend making a live demo — press Ctrl-M in the question editor — so that we can see exactly what layout your code achieves. \$\endgroup\$ Nov 24, 2017 at 0:56
  • \$\begingroup\$ What you have there is a conditional expression, which always produces a value. You are not interested in that value, however. In this case, an if-statement seems more intuitive or semantically correct. \$\endgroup\$
    – le_m
    Nov 24, 2017 at 1:22

1 Answer 1

5
\$\begingroup\$

This is not the place to ask for code fix, but let me help you since its code review.

var sponsorshipImagesLength = $('.field-name-field-sponsorship-image').length;

var evoMarginTop = sponsorshipImagesLength > 0 ? '-260px' : '-300px';
evoJustIn.css('margin-top', evoMarginTop);

Now you have devided your code into smaller blocks that are more readable for you, but also for other people working on your code.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.