Skip to content

Scrollbar Animate Dropdown Directive

v-animate-dropdown

A custom Vue directive that provides smooth animation effects for dropdown menus in a sidebar. It smoothly expands and collapses dropdown content based on the parent element's state.


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)

  • Triggered when the directive is mounted to an element.
  • Finds the parent .sidebar-dropdown element.
  • Sets up animation speed (700 units per second).
  • Defines internal functions:
    • expand(): Calculates duration based on element height, sets transitions, and removes styling after animation completes.
    • collapse(): Similar to expand but reduces height to 0px.
  • Creates a MutationObserver to watch for class changes on the parent element.
  • Initializes the element state based on whether parent has the sidebar-item-open class.
  • Stores the observer and timeout references for cleanup.

unmounted(el)

  • Triggered when the directive is unmounted.
  • Disconnects the MutationObserver to prevent memory leaks.
  • Clears any pending timeouts.

Usage

vue
<template>
  <div class="sidebar-dropdown" :class="{ 'sidebar-item-open': isOpen }">
    <div class="dropdown-header" @click="isOpen = !isOpen">
      Menu Item
    </div>
    <div v-scrollbar-animate-dropdown>
      <!-- Dropdown content -->
      <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ScrollbarAnimateDropdown } from '@/directives/ScrollbarAnimateDropdown';

const isOpen = ref(false);
</script>

Behavior

  • Animation speed is set to 700 units (px/second).
  • When the parent receives the class sidebar-item-open, the element smoothly expands to its full height.
  • When the class is removed, the element smoothly collapses to 0px height.
  • Animation duration is calculated dynamically based on the element's scroll height.
  • The directive cleans up observers and timeouts when unmounted to prevent memory leaks.

Notes

  • The directive must be applied to an element that is a child of an element with the class sidebar-dropdown.
  • The parent element should toggle the class sidebar-item-open to indicate open/closed state.
  • Uses MutationObserver to detect changes to the parent element's class list.
  • Animation is achieved by manipulating CSS properties (height, transition, overflow).
  • Compatible with all modern browsers that support MutationObserver API.
  • For elements that dynamically change content, you may need to re-initialize the directive.