Skip to main content

Part 3 / Transitions / Custom JS transitions

一般に、トランジションには可能な限りCSSを用いるべきですが、いくつかのトランジション効果に関してはJavaScriptを用いないと実現できません。その一例がタイプライター効果です。

function typewriter(node, { speed = 1 }) {
	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 * 0.01);

	return {
		duration,
		tick: (t) => {
			const i = Math.trunc(text.length * t);
			node.textContent = text.slice(0, i);
		}
	};
}

Next: Transition events

initialising