jjy9331 / pfjjy_nextjs

0 stars 1 forks source link

typewriter-effect #9

Open jjy9331 opened 1 year ago

jjy9331 commented 1 year ago

Ref

https://www.geeksforgeeks.org/how-to-add-typewriter-effect-in-next-js/ https://codepen.io/cyrilvernier/pen/wvwZBaq https://github.com/tameemsafi/typewriterjs

jjy9331 commented 1 year ago

GPT example

import React, { useRef, useEffect, useState } from "react";
import Typewriter from "typewriter-effect";

export default function ScrollTypewriter() {
  const [scrollY, setScrollY] = useState(0);
  const typewriterRef = useRef(null);

  useEffect(() => {
    const handleScroll = () => {
      setScrollY(window.scrollY);
    };

    window.addEventListener("scroll", handleScroll);

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  useEffect(() => {
    const { current: typewriterElement } = typewriterRef;

    if (scrollY > 500 && scrollY <= 1000) {
      // Start the typewriter animation when scrollY is within the specified range
      const typewriter = new Typewriter(typewriterElement, {
        strings: ["Hello", "World"],
        autoStart: true,
        delay: 50,
      });
    }
  }, [scrollY]);

  return (
    <div>
      <div style={{ height: "1500px" }}></div> {/* Space for scrolling */}
      <div ref={typewriterRef}></div> {/* Element where the typewriter effect will be applied */}
    </div>
  );
}
jjy9331 commented 1 year ago

GPT example

import React, { useRef, useEffect, useState } from "react";
import Typewriter from "typewriter-effect";

export default function ScrollTypewriter() {
  const [scrollY, setScrollY] = useState(0);
  const typewriterRef = useRef(null);

  useEffect(() => {
    const handleScroll = () => {
      setScrollY(window.scrollY);
    };

    window.addEventListener("scroll", handleScroll);

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  useEffect(() => {
    const { current: typewriterElement } = typewriterRef;

    if (scrollY > 500 && scrollY <= 1000) {
      // Start the typewriter animation when scrollY is within the specified range
      const typewriter = new Typewriter(typewriterElement, {
        strings: ["Hello", "World"],
        autoStart: true,
        delay: 50,
      });
    }
  }, [scrollY]);

  return (
    <div>
      <div style={{ height: "1500px" }}></div> {/* Space for scrolling */}
      <div ref={typewriterRef}></div> {/* Element where the typewriter effect will be applied */}
    </div>
  );
}

not working, we have to change to html tag like this

https://www.npmjs.com/package/typewriter-effect