2

Based on the React documentation that I looked at, I think I would use "useRef" to update a function, but I'm not sure. I want to fire an event to mute a video there is a scroll event. Right now I'm using onClick to play/pause the video.

Video.js

import React, { useRef, useState } from "react";
import "./Video.css";

function Video({ url }) {
  const [muted, setMuted] = useState(true);
  const [playing, setPlaying] = useState(false);
  const videoRef = useRef(null);

  var Chrome =
    navigator.userAgent.includes("Chrome") &&
    navigator.vendor.includes("Google Inc");

  const onVideoPress = () => {
    if (playing && !Chrome) {
      videoRef.current.pause();
      setPlaying(false);
      setMuted(true);
    } else if (playing && Chrome) {
      videoRef.current.pause();
      setPlaying(false);
      setMuted(false);
    } else {
      videoRef.current.play();
      setPlaying(true);
      setMuted(false);
    }
  };

  return (
    <div className="video">
      <video
        className="video__player"
        autoPlay={true}
        loop={true}
        muted={muted}
        playsInline={true}
        // controls
        ref={videoRef}
        onClick={onVideoPress}
      >
        <source className="video__controls" src={url} type="video/mp4"></source>
      </video>
      {/* <VideoFooter /> */}
    </div>
  );
}

export default Video;

This is not the same How to add scroll event in react component because I am not extending the function as a component.

1

2 Answers 2

1

I used onScroll={()=> someFunc()}

Sign up to request clarification or add additional context in comments.

Comments

0

Using scroll event listener you should be able to achieve what you are seeking.

  • inside useEffect define an event scroll listener

    document.addEventListener('scroll', function(e) {
    
           // your logic goes here
          });
    

4 Comments

would I use onScroll in my video element and call the function there?
I tried this: useEffect(() => { document.addEventListener("scroll", function (e) { e.setMuted(true) }); }); is that what you meant?
when I add useEffect(() => { document.addEventListener("scroll", function (e) { e.alert("hi"); }); }); nothing happens
don't use e.alert. Just try alert("hi"). It should work. Also don't do e.setMuted(true), e is the event object. Try using setMuted(true) Directly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.