kdizzle
kdizzle

Reputation: 627

How to fire off a function at start of a video and a different function when the user pauses and presses play to continue watching the video?

Currently, I have a video.js player with React. My goal is to fire off a function when the user starts playing the video and to fire a separate function when the user plays the video back again after pausing the video(let's call this the "continue" event). How can I achieve this without firing the incorrect function at start and continue?

I've looked at several different HTML media events such as 'play' and 'playing', however the "continue" function is still firing at start.

Here's what I have:

const VideoPlayer = ({ handleOnPlayContinue, handleOnStart }) => {
  const [hasStarted, setHasStarted] = useState(false);
  
  useEffect(() => {
      videoJSPlayer.on('play'), () => {
        setHasStarted(true);
      };
      videoJSPlayer.on('playing'), () => {
        handleOnPlayContinue();
      };
    }, [videoJSPlayer, handleOnPlayContinue]);
  
  useEffect(() => {
    if (hasStarted) {
      handleOnStart();
    }
  }, [hasStarted, handleOnStart]);
}

Should I be toggling another boolean state on 'pause' and use that boolean flag to fire my continue function? I thought of setting another state to manage when the user is continuing the video after pausing, but wanted to know if there's another HTML media event that I can leverage.

Thanks for any tips and answers you may have!

Upvotes: 0

Views: 210

Answers (1)

gloo
gloo

Reputation: 721

I don't believe there is a relevant HTML media event; you are going to have to manage it yourself with state and within just the play event. See if the below works for what you are trying to achieve (I have not been able to test it). Keep in mind that changes to state in useEffect aren't updated synchronously, and hasStarted needs to be in the dependency array otherwise the event will reference stale state variables. We also want to clean up event listeners between useEffect calls.

const VideoPlayer = ({ handleOnPlayContinue, handleOnStart }) => {
  const [hasStarted, setHasStarted] = useState(false);

  useEffect(() => {
    videoJSPlayer.on("play", () => {
      if (!hasStarted) {
        handleOnStart();
        setHasStarted(true);
      } else {
        handleOnPlayContinue();
      }
    });
    return () => {
      videoJSPlayer.off("play");
    };
  }, [hasStarted, handleOnPlayContinue, handleOnStart, videoJSPlayer]);
};

Upvotes: 1

Related Questions