getScrollPosition.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @typechecks
  8. */
  9. 'use strict';
  10. var getDocumentScrollElement = require('./getDocumentScrollElement');
  11. var getUnboundedScrollPosition = require('./getUnboundedScrollPosition');
  12. /**
  13. * Gets the scroll position of the supplied element or window.
  14. *
  15. * The return values are bounded. This means that if the scroll position is
  16. * negative or exceeds the element boundaries (which is possible using inertial
  17. * scrolling), you will get zero or the maximum scroll position, respectively.
  18. *
  19. * If you need the unbound scroll position, use `getUnboundedScrollPosition`.
  20. *
  21. * @param {DOMWindow|DOMElement} scrollable
  22. * @return {object} Map with `x` and `y` keys.
  23. */
  24. function getScrollPosition(scrollable) {
  25. var documentScrollElement = getDocumentScrollElement(scrollable.ownerDocument || scrollable.document);
  26. if (scrollable.Window && scrollable instanceof scrollable.Window) {
  27. scrollable = documentScrollElement;
  28. }
  29. var scrollPosition = getUnboundedScrollPosition(scrollable);
  30. var viewport = scrollable === documentScrollElement ? scrollable.ownerDocument.documentElement : scrollable;
  31. var xMax = scrollable.scrollWidth - viewport.clientWidth;
  32. var yMax = scrollable.scrollHeight - viewport.clientHeight;
  33. scrollPosition.x = Math.max(0, Math.min(scrollPosition.x, xMax));
  34. scrollPosition.y = Math.max(0, Math.min(scrollPosition.y, yMax));
  35. return scrollPosition;
  36. }
  37. module.exports = getScrollPosition;