That error is thrown any time you try to set the currentTime
before the browser knows the duration
of the video. The duration is part of the "metadata", which is typically in the header of the video file and includes the height and width.
Usually, if you have a video element without a preload
attribute, the browser will try to at least load the metadata soon after you load the page. But, depending on the specifics of the browser, the rest of the content on the page and the speed of the network connection, it may not happen until after you've scrolled at least once.
A solution looks something like this.
/*
memoize video, window and document so you don't have to create and
garbage-collect new objects every time you scroll
*/
var video = $('#trees').get(0),
$window = $(window),
$document = $(document);
function updateVideo() {
var duration = video.duration,
scrollPosition = window.scrollY;
if (duration) {
video.currentTime = (scrollPosition / ($document.height() - $window.height())) * duration;
}
}
// update video every time you scroll
$window.scroll(updateVideo);
// update video when metadata has loaded
$(video).on('loadedmetadata', updateVideo);
That should make the error go away. If you try this and the loadedmetadata
event never fires, try adding this to the end to force it:
video.load();
Edit: Defined and set scrollPosition
. Here is a working example: http://jsbin.com/vurap/1/edit