0

I have used a bit of jQuery to fire an if function. When I try to simplify the equation using vanilla javascript's ternary operands it doesn't seem to work.

What am I doing wrong?

if(windowBottom > objectBottom) {

    $(this).animate({opacity: '1'}, 1500);
    $(this).addClass('item-play__right');
}
//works fine

windowBottom > objectBottom ? $(this).animate({opacity: '1'}, 1500).addClass('item-play__right');
//doesn't work
vol7ron
  • 40,809
  • 21
  • 119
  • 172
S Roughton
  • 73
  • 5
  • Possible duplicate of [How to write this ternary operator with jQuery?](https://stackoverflow.com/questions/6595585/how-to-write-this-ternary-operator-with-jquery) – Ryan Schaefer Mar 03 '18 at 15:24
  • Don't use ternary operator instead of `if ..else`, use the operator only where it's expected, i.e. inside an expression. – Teemu Mar 03 '18 at 15:24
  • Questioning if you know what a ternary operator is, based on your *doesn't work* example. What did you expect it to do? – vol7ron Mar 03 '18 at 15:33

3 Answers3

1

Yes it can be done but it requires usage of both ? & :

windowBottom > objectBottom ? ($(this).animate({opacity:"1"}, 
1500).addClass("item-play__right")) :'';

Without ternary operator the snippet can also be written as

windowBottom > objectBottom && ($(this).animate({opacity:"1"}, 
1500).addClass("item-play__right"));
brk
  • 48,835
  • 10
  • 56
  • 78
0

This is not a valid ternary syntax you're using, there should be two possible outcome separated by a : character.

Also, if you're using itfor side-effects and not to compute a value, it is better to use an if/ else

Axnyff
  • 9,213
  • 4
  • 33
  • 37
0

You need both ? and : otherwise it will result in syntax error.

windowBottom > objectBottom ? $(this).animate({opacity: '1'}, 1500).addClass('item-play__right') : "";
void
  • 36,090
  • 8
  • 62
  • 107