0

Possible Duplicate:
JavaScript OR (||) variable assignment explanation

Can someone help explain what this line does, and how?

var scrollTop = html.scrollTop || body && body.scrollTop || 0;
Community
  • 1
  • 1
socm_
  • 783
  • 11
  • 28

1 Answers1

4

You can think of the logic a bit like this...

if (html.scrollTop > 0) {
    scrollTop = html.scrollTop;
    return;
}

if (body != undefined) {
    if (body.scrollTop > 0) {
         scrollTop = body.scrollTop;
         return;
    }

}

scrollTop = 0;
return;

It is setting the scrollTop variable using a list of priorities.

  1. First, try to use html.scrollTop if it exists and is greater than zero.
  2. If not, then make sure that body exists and use body.scrollTop if it is greater than zero.
  3. If all else fails, just set it to 0
njr101
  • 9,499
  • 7
  • 39
  • 56
  • is that strict (html.scrollTop > 0) or we can write (html.scrollTop)?? Thanks – socm_ Nov 05 '12 at 15:39
  • 1
    In this case you could just write `if (html.scrollTop)`. I used the longer notation to be more explicit in the explanation. In JavaScript the `if`statement can be used to check for any truthy condition (not zero, not empty string, not null, etc.) But you need to be careful if you think `scrollTop` could be a negative number. – njr101 Nov 05 '12 at 15:41