0

I'm looking to create a video parallax background, but I want that the progress of the video corresponds to where I am on my webpage.

For example :

  • When im on the top of the page the video is at 0 seconds,
  • in the middle at 50% of its total runtime
  • and finishes only when I reach the bottom of the page.
Marine Le Borgne
  • 1,036
  • 2
  • 11
  • 39
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Apr 01 '22 at 10:53

1 Answers1

2

You have to break down the big problem into smaller problems.

First, you need to get your video's duration :

var vid = document.getElementById("myVideo");
duration = vid.duration;

Next, you need to get the scroll amount in percentage

function getVerticalScrollPercentage (elm) {
  var p = elm.parentNode
  return (elm.scrollTop || p.scrollTop) / (p.scrollHeight - p.clientHeight ) * 100
}

Next, you need to dynamically set your video's currentTime (in seconds), you can do it this way :

vid.currentTime = duration * percentage / 100;

And finally, you need to set the currentTime again, whenever the scroll amount changes. That is achieved by using an event listener, on the body for example.

object.addEventListener("scroll", myScript);

Now put it all together :)

Marine Le Borgne
  • 1,036
  • 2
  • 11
  • 39
  • hm... seems i dont really get it :D i tried it in a fiddle: https://jsfiddle.net/Pinnhead1987/efq6awd1/61/ but it throws me an ReferenceError – Gerhard Klein Apr 04 '22 at 06:25
  • I gave you an example of how it works, but you still need to rename `myScript` to the actual name of the script and object to the container that scrolls. – Marine Le Borgne Apr 04 '22 at 10:03
  • Here's an example put together, but you still need to tweak some values. https://jsfiddle.net/8kLvto70/35/ – Marine Le Borgne Apr 04 '22 at 10:28