Skip to content

Scrollbar Scroll Directives

v-hide-scrollbar

A custom Vue directive that provides auto-hiding scrollbars. The scrollbar is hidden by default and appears during scrolling, then disappears after a period of inactivity. When Scrollbar is hovered then also it appears.


Props (Binding Value)

None. This directive does not accept any binding values.


Slots

N/A (used as a directive, not a component).


Emits

None (directives do not emit events).


Functions

mounted(el, _binding)

  • Triggered when the directive is mounted to an element.
  • Initializes variables to track timeouts and the last hide timestamp.
  • Immediately adds the hide-scrollbar class to the element.
  • Sets up three internal functions:
    • showScrollbar(): Removes the hide-scrollbar class to make scrollbars visible.
    • hideScrollbar(): Adds the hide-scrollbar class and updates the last hide timestamp.
    • onScroll(): Event handler that:
      • Shows the scrollbar if it's been hidden for at least 100ms
      • Clears any existing hide timeout
      • Sets a new timeout to hide the scrollbar after 1 second of inactivity
  • Adds the scroll event listener to the element.
  • Stores the handler reference in a WeakMap for cleanup purposes.

unmounted(el)

  • Triggered when the directive is unmounted.
  • Retrieves the stored event handler from the WeakMap.
  • Removes the scroll event listener from the element.
  • Deletes the reference from the WeakMap to prevent memory leaks.

Usage

vue
<template>
  <div class="overflow-y-auto h-60" v-scrollbar-scroll>
    <!-- Content that might overflow and require scrolling -->
    <div v-for="n in 20" :key="n">
      Item {{ n }}
    </div>
  </div>
</template>

<style>
/* Required CSS for the directive to work */
.hide-scrollbar::-webkit-scrollbar {
  width: 0;
  height: 0;
  opacity: 0;
}

.hide-scrollbar {
  -ms-overflow-style: none; /* IE and Edge */
  scrollbar-width: none; /* Firefox */
}
</style>

Behavior

  • Scrollbars are hidden by default (using the hide-scrollbar class).
  • When the user scrolls, the scrollbars appear immediately.
  • After 1 second of no scrolling activity, the scrollbars disappear again.
  • The directive enforces a minimum 100ms between hide/show cycles to prevent flickering.

Notes

  • Requires corresponding CSS (as shown in usage example) to actually hide the scrollbars.
  • Uses a WeakMap to store event handlers, which helps prevent memory leaks.
  • To work properly, the element must have overflow content and be set to overflow: auto or overflow: scroll.
  • Useful for creating a cleaner UI while still maintaining scrolling functionality.
  • The 1-second hide delay and 100ms reappearance threshold provide a balanced user experience.