While you should generally use CSS for transitions as much as possible, there are some effects that can't be achieved without JavaScript, such as a typewriter effect:
function typewriter(node, { speed = 50 }) {
const valid = (
node.childNodes.length === 1 &&
node.childNodes[0].nodeType === Node.TEXT_NODE
);
if (!valid) {
throw new Error(`This transition only works on elements with a single text node child`);
}
const text = node.textContent;
const duration = text.length * speed;
return {
duration,
tick: t => {
const i = ~~(text.length * t);
node.textContent = text.slice(0, i);
}
};
}
App.svelte
xxxxxxxxxx
22
1
<script>
2
let visible = false;
3
4
function typewriter(node, { speed = 50 }) {
5
// implementation goes here
6
7
return {
8
9
};
10
}
11
</script>
12
13
<label>
14
<input type="checkbox" bind:checked={visible}>
15
visible
16
</label>
17
18
{#if visible}
19
<p in:typewriter>
20
The quick brown fox jumps over the lazy dog
Console
xxxxxxxxxx
141
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
add_render_callback,
5
append,
6
attr,
7
create_in_transition,
8
detach,
9
element,
10
empty,
11
init,
12
insert,
13
listen,
14
noop,
15
safe_not_equal,
16
space,
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */