summaryrefslogtreecommitdiff
path: root/assets/js/morph.js
blob: aea6dffd018900f645b91da0dd89941f547c642b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@._-";

function morph(element, target) {
	clearInterval(element._timer);

	const start = element.textContent;
	const length = Math.max(start.length, target.length);

	let progress = 0;

	element._timer = setInterval(() => {
		progress += 0.05;

		const currentLength = Math.round(
			start.length + (target.length - start.length) * progress
		);

		let output = "";

		for (let i = 0; i < currentLength; i++) {
			if (progress > i / currentLength + 0.2 && target[i]) {
				output += target[i];
			} else {
				output += CHARS[Math.floor(Math.random() * CHARS.length)];
			}
		}

		element.textContent = output;

		if (progress >= 1) {
			clearInterval(element._timer);
			element.textContent = target;
		}
	}, 15);
}

for (const link of document.querySelectorAll(".morph")) {
	const original = link.textContent;
	const alternate = link.dataset.alt;

	link.addEventListener("mouseenter", () => morph(link, alternate));
	link.addEventListener("mouseleave", () => morph(link, original));
}