javascript get property from chain function

Viewed 29

I need to make a function like this "device.browser.scroll().top" how do I make a function do that and get the value from and object, my code says undefined all the time.

let device = {};
device.browser = {};
device.browser.scroll = (el = window) => {
      
  return {
    top: el.pageXOffset || el.scrollLeft,
    Left: el.pageYOffset || el.scrollTop,
  }
}

console.log('scrollTop', device.browser.scroll().top);
html, body {
  height: 100%;
}

.wrapper div {
  height: 100vh;
}

.wrapper div:nth-child(1) {
  background: red;
}


.wrapper div:nth-child(2) {
  background: green;
}


.wrapper div:nth-child(3) {
  background: blue
}
<div class="wrapper">
  <div></div>
  <div></div>
  <div></div>
</div>

1 Answers

The problem is that || will evaluate to the right side if the left side is falsey, and 0 is falsey, despite containing the numeric information you want. You could use ?? instead, which will only evaluate to the right side if the left side is undefined or null:

return {
  top: el.pageXOffset ?? el.scrollLeft,
  Left: el.pageYOffset ?? el.scrollTop,
}

let device = {};
device.browser = {};
device.browser.scroll = (el = window) => {
      
  return {
    top: el.pageXOffset ?? el.scrollLeft,
    Left: el.pageYOffset ?? el.scrollTop,
  }
}

console.log('scrollTop', device.browser.scroll().top);
html, body {
  height: 100%;
}

.wrapper div {
  height: 100vh;
}

.wrapper div:nth-child(1) {
  background: red;
}


.wrapper div:nth-child(2) {
  background: green;
}


.wrapper div:nth-child(3) {
  background: blue
}
<div class="wrapper">
  <div></div>
  <div></div>
  <div></div>
</div>

Or, for older browsers, use the conditional operator to test for undefined:

return {
  top: el.pageXOffset === undefined ? el.scrollLeft : el.pageXOffset,
  Left: el.pageYOffset === undefined ? el.scrollTop : el.pageYOffset,
}
Related