0

I am trying to understand this implementation of mousewheel.jquery.

$('.page').mousewheel(function(event, delta) {
    event.preventDefault(); // if you want to prevent the window from scrolling

    $(this).animate({left: (delta>0 ? '+' : '-')+'40px'});
});

What does ? and : do in:

$(this).animate({left: (delta>0 ? '+' : '-')+'40px'});
War10ck
  • 12,387
  • 7
  • 41
  • 54
CAPTN_BLCKA
  • 65
  • 1
  • 7
  • 3
    possible duplicate of [JS How to use the ?: (ternary) operator](http://stackoverflow.com/questions/6259982/js-how-to-use-the-ternary-operator) – Erik Philips Oct 24 '14 at 18:56
  • 2
    It's the [ternary operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) – Lucas Trzesniewski Oct 24 '14 at 18:57
  • jQuery is a wrapper on Javascript. That's just a Javascript inline if-then-else construct. `exp1 ? exp2 : exp3` Means if `exp1` is true, then `exp2` is executed. Otherwise, `exp3` is executed. – lurker Oct 24 '14 at 18:57

6 Answers6

3

?: is the ternary operator in javascript.

The code

$(this).animate({left: (delta>0 ? '+' : '-')+'40px'});

is equivalent to:

if (delta > 0) {
    $(this).animate({left: '+40px'});
} else {
    $(this).animate({left: '-40px'});
}
Ananth
  • 4,227
  • 2
  • 20
  • 26
0

It's the ternary operator. It checks if the bool check preceding the ? is true. If so, it runs the code before : otherwise the code after the :.

In this instance, if delta > 0 returns true, it uses +, otherwise it uses -.

Dave Zych
  • 21,581
  • 7
  • 51
  • 66
0

This is called a ternary operator. Essentially, the line of code you posted is the same as:

if(delta >0) { 
   //output +
} else {
   //output -
}
War10ck
  • 12,387
  • 7
  • 41
  • 54
0

it translates into:

if(delta > 0)
   return'+';
else
   return '-';
johnny 5
  • 19,893
  • 50
  • 121
  • 195
0

This works like an IF-statement

condition ? true : false;


if(delta>0) {
 return "+";
}
else {
 return "-";
}
Daniel
  • 4,816
  • 3
  • 27
  • 31
0

The ? and : is an alternative way of writing an if-else statement

x = y ? z : k

is the same as

if (y){
 x = z;
}else{
 x = k;
}
L.H
  • 325
  • 1
  • 7