How to get clicked position of div element for progressbar

Viewed 316

I have a HTML5 Video panel in my app. I managed to make a progressbar which is working perfectly. But I also want to ability to change currentTime of the video by clicking to any position on progressbar.

How can I get current position as ratio using React? I searched progressbar components on google but it seems none of them give value of clicked position but just display.

Or simply, when user clicks on different position of the progressbar, I want to change/get value of progressbar to that position.

enter image description here

Update:

I have updated demo and it seems progressbar gone crazy when click multiple times and it seems not close to the clicked position either.

enter image description here

Demo: https://stackblitz.com/edit/react-ts-zudlbe?file=index.tsx

1 Answers

This is the whole component I tested it on. Seems to work

const ProgressBar = ({ duration, progress }: ProgressProps) => {
  return (
    <div
      onClick={(event: React.MouseEvent<HTMLDivElement>) => {
        // duration is the video duration. For example 152.
        // How can i catch the % (ratio) of clicked position of this progrssbar?
        // then I will send this % (lets say 5) to the seek function like:
        const x = (event.clientX * duration) / event.currentTarget.offsetWidth; // how to get sec?
        callback(x);
      }}
      style={{
        backgroundColor: "#ddd",
        borderRadius: 3,
        flex: 1,
        height: 6,
        overflow: "hidden",
        position: "relative"
      }}
    >
      <Progress progress={progress} />
    </div>
  );
};
Related