Skip to main content
InterviewHubPRO
Section Overview
Q48

Question 48 of 50

Part 3: Advanced Internals, Scale & Production Architecture (Senior / Lead)

96%
Svelte & SvelteKit (50 Qs)•Part 3: Advanced Internals, Scale & Production Architecture (Senior / Lead)

Svelte Actions: The `use:action` Directive for Direct DOM Lifecycle.

senior LevelCode ExampleDirectivesState ManagementLifecycle

In Simple Words: An Action is an elemental Svelte function attached to an HTML node via use:actionName. It is called when the element is created in the DOM and receives the DOM element reference.

typescript
// useTooltip.ts: Action definition
export function tooltip(node: HTMLElement, text: string) {
  const tip = document.createElement('div');
  tip.textContent = text;
  tip.className = 'tooltip-bubble hidden';
  node.appendChild(tip);

  const show = () => tip.classList.remove('hidden');
  const hide = () => tip.classList.add('hidden');

  node.addEventListener('mouseenter', show);
  node.addEventListener('mouseleave', hide);

  return {
    update(newText: string) { tip.textContent = newText; },
    destroy() {
      node.removeEventListener('mouseenter', show);
      node.removeEventListener('mouseleave', hide);
      tip.remove();
    }
  };
}

// In Svelte Template:
// <button use:tooltip={'Click to save changes'}>Save</button>