Home > Net >  Loop video with hover ReactJS
Loop video with hover ReactJS

Time:10-28

I am trying to autoplay a video when rendered, but only once. On the hover effect, I would like it to play the video with a loop. I have tried to use event.target.play() on mouseOver but have had no luck.

Any help would be greatly appreciated :)

<video 
  className="videos" 
  autoPlay={true} 
  onm ouseOver={event => event.target.play()} 
  onm ouseOut={event => event.target.pause()} 
  muted={true}
  src={prompt}>
</video>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can use onEnded event along with mouseover to loop it. Also using useRef makes it easy to set/play instead of passing event from all the callbacks. Check below code,

import { useEffect, useRef, useState } from "react";
import testVideo from "./testVideo.mp4";

export default function App() {
  const ref = useRef(null);
  const [focus, setFocus] = useState(false);

  const loop = () => {
    ref.current.play();
  };

  const onEndedLoop = () => {
    if (focus) loop(); // when ended check if its focused then loop
  };

  useEffect(() => {
    if (focus) loop(); // when focused then loop
  }, [focus]);

  return (
    <div className="App">
      <h2>Loop video with hover ReactJS!</h2>
      <video
        id="video"
        ref={ref}
        style={{ width: "300px" }}
        autoPlay
        onMouseOver={() => setFocus(true)}
        onm ouseOut={() => setFocus(false)}
        muted={true}
        src={testVideo}
        onEnded={onEndedLoop}
      ></video>
    </div>
  );
}

check working demo - https://codesandbox.io/s/loop-video-on-hover-qegu7

CodePudding user response:

@Madhuri has good answer (Which I upvoted). However, if we add a function to pause loop when not focused, that will loop the video only when in focus and stop when not hovering over or not in focus.

const loop = () => {
    ref.current.play();
  };

  const pauseLoop = () => {
    ref.current.pause();
  };

  const onEndedLoop = () => {
    if (focus) loop(); // when ended check if its focused then loop
  };

  useEffect(() => {
    if (focus) loop(); // when focused then loop
    if (!focus) pauseLoop(); // when not focused then pause loop
  }, [focus]);
  • Related