xbase-2.x-dev/js/scrollbar-width.js

js/scrollbar-width.js
(function () {

  /**
   * Debounce function.
   * Copy-paste from /core/misc/debounce.js
   * @TODO Remove after core/drupal.debounce library remove dependency of core/drupal
   */
  function debounce(func, wait, immediate) {
    let timeout;
    let result;
    return function (...args) {
      const context = this;
      const later = function () {
        timeout = null;
        if (!immediate) {
          result = func.apply(context, args);
        }
      };
      const callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) {
        result = func.apply(context, args);
      }
      return result;
    };
  }

  /**
   * Return scrollbar width in px.
   */
  window.getScrollbarWidth = function (element) {
    element = element ? element : document.documentElement;

    const elementOriginalOverflowYPropertyValue = element.style.overflowY;

    element.style.overflowY = 'hidden';
    const widthWithoutScrollbar = element.getBoundingClientRect().width;

    element.style.overflowY = 'scroll';
    const widthWithScrollbar = element.getBoundingClientRect().width;

    const scrollbarWidth = widthWithoutScrollbar - widthWithScrollbar;

    element.style.overflowY = elementOriginalOverflowYPropertyValue;

    return Math.round(scrollbarWidth * 100) / 100;
  }

  /**
   * Calculate and set css variable --scrollbar-width.
   */
  function updateScrollbarWidthVariable() {
    //console.log('updateScrollbarWidthVariable');
    document.documentElement.style.setProperty('--scrollbar-width', getScrollbarWidth() + 'px');
  }

  // Initial calculate scrollbar width
  updateScrollbarWidthVariable();

  // Calculate scrollbar width on window resize.
  // ResizeObserver not used because he run after added any content in page.
  window.addEventListener('resize', debounce(updateScrollbarWidthVariable, 100));

})();

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc