From 51c4c48e1e77d809b4d83773d42468ee26400175 Mon Sep 17 00:00:00 2001 From: Adam Laki Date: Fri, 15 Mar 2024 14:44:00 +0100 Subject: [PATCH] Add observer to typing effect so it stops if not in viewport --- src/js/typewriter-init.js | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/js/typewriter-init.js b/src/js/typewriter-init.js index 86ae5f8..9046230 100644 --- a/src/js/typewriter-init.js +++ b/src/js/typewriter-init.js @@ -2,14 +2,34 @@ if (!document.querySelector('#typewriter')) return; const typewriter = document.querySelector('[data-typewriter]').dataset.typewriter.split(', '); + const heroTitle = document.querySelector('.hero__title'); + + const options = { + root: null, + rootMargin: '0px', + threshold: 0.5 + }; if (typewriter.length <= 1) return; - new Typewriter('#typewriter', { + const typing = new Typewriter('#typewriter', { strings: typewriter, autoStart: true, cursor: '', loop: true, pauseFor: 2500, }); + + const callback = (entries) => { + entries.forEach((entry) => { + if (entry.isIntersecting) { + typing.start(); + } else { + typing.pause(); + } + }); + }; + + const observer = new IntersectionObserver(callback, options); + observer.observe(heroTitle); })();