Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
Loop video with hover ReactJS

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} 
  onMouseOver={event => event.target.play()} 
  onMouseOut={event => event.target.pause()} 
  muted={true}
  src={prompt}>
</video>

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)}
        onMouseOut={() => setFocus(false)}
        muted={true}
        src={testVideo}
        onEnded={onEndedLoop}
      ></video>
    </div>
  );
}

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

about 4 years ago · Juan Pablo Isaza Report

0

@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]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!