scrollbar.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Slightly modified, but without dependancies:
  2. // https://raw.githubusercontent.com/malte-wessel/react-custom-scrollbars/master/src/utils/getScrollbarWidth.js
  3. let scrollbarWidth: number | null = null;
  4. export default function getScrollbarWidth() {
  5. if (scrollbarWidth !== null) {
  6. return scrollbarWidth;
  7. }
  8. if (typeof document !== 'undefined') {
  9. const div = document.createElement('div');
  10. const newStyles = {
  11. width: '100px',
  12. height: '100px',
  13. position: 'absolute',
  14. top: '-9999px',
  15. overflow: 'scroll',
  16. MsOverflowStyle: 'scrollbar',
  17. };
  18. Object.keys(newStyles).map(style => {
  19. // @ts-ignore
  20. div.style[style] = newStyles[style];
  21. });
  22. document.body.appendChild(div);
  23. scrollbarWidth = div.offsetWidth - div.clientWidth;
  24. document.body.removeChild(div);
  25. } else {
  26. scrollbarWidth = 0;
  27. }
  28. return scrollbarWidth || 0;
  29. }
  30. const hasNoOverlayScrollbars = getScrollbarWidth() > 0;
  31. export const addClassIfNoOverlayScrollbar = (classname: string, htmlElement: HTMLElement = document.body) => {
  32. if (hasNoOverlayScrollbars) {
  33. htmlElement.classList.add(classname);
  34. }
  35. };