scrollbar.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // Slightly modified, but without dependancies:
  2. // https://raw.githubusercontent.com/malte-wessel/react-custom-scrollbars/master/src/utils/getScrollbarWidth.js
  3. let scrollbarWidth = 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. div.style[style] = newStyles[style];
  20. });
  21. document.body.appendChild(div);
  22. scrollbarWidth = (div.offsetWidth - div.clientWidth);
  23. document.body.removeChild(div);
  24. } else {
  25. scrollbarWidth = 0;
  26. }
  27. return scrollbarWidth || 0;
  28. }
  29. const hasNoOverlayScrollbars = getScrollbarWidth() > 0;
  30. export const addClassIfNoOverlayScrollbar = (classname: string, htmlElement: HTMLElement = document.body) => {
  31. if (hasNoOverlayScrollbars) {
  32. htmlElement.classList.add(classname);
  33. }
  34. };