Skip to main content

Like transitions and animations, an action can take an argument, which the action function will be called with alongside the element it belongs to.

In this exercise, we want to add a tooltip to the <button> using the Tippy.js library. The action is already wired up with use:tooltip, but if you hover over the button (or focus it with the keyboard) the tooltip contains no content.

First, the action needs to accept some options and pass them to Tippy:

App.svelte
function tooltip(node, options) {
	const tooltip = tippy(node, options);

	return {
		destroy() {
			tooltip.destroy();
		}
	};
}

Then, we need to pass some options into the action:

App.svelte
<button use:tooltip={{ content, theme: 'material' }}>
	Hover me
</button>

The tooltip now works — almost. If we change the text in the <input>, the tooltip will not reflect the new content. We can fix that by adding an update method to the returned object.

App.svelte
function tooltip(node, options) {
	const tooltip = tippy(node, options);

	return {
		update(options) {
			tooltip.setProps(options);
		},
		destroy() {
			tooltip.destroy();
		}
	};
}

Next: Advanced bindings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script>
	import tippy from 'tippy.js';
	import 'tippy.js/dist/tippy.css';
	import 'tippy.js/themes/material.css';
 
	let content = 'Hello!';
 
	function tooltip(node) {
		const tooltip = tippy(node);
 
		return {
			destroy() {
				tooltip.destroy();
			}
		};
	}
</script>
 
<input bind:value={content} />
 
<button use:tooltip>
	Hover me
</button>
initialising