Xen_mar
Xen_mar

Reputation: 9752

How to reset a video tag with javascript?

I'm currently working with a video tag:

<video loop class="video">
    <source src="..." type="video/mp4"></source>
</video>

It is tied to an intersection observer that triggers the autoplay attribute on it. When the video is not visible I want to reset it so it returns to its pristine state (showing the poster).

Currently I'm doing this:

const videoNote = document.querySelector("video")
videoNote.pause()
videoNote.load()

This works but I'm having trouble with the browser reloading my page (which may or may not is caused by the .load method.

Is there a better way to reset a video?

Upvotes: 0

Views: 933

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075905

Rather than load, if the goal is to move the video back to the very beginning, I'd set currentTime to 0. From MDN's video documentation:

currentTime

Reading currentTime returns a double-precision floating-point value indicating the current playback position of the media specified in seconds. If the media has not started playing yet, the time offset at which it will begin is returned. Setting currentTime sets the current playback position to the given time and seeks the media to that position if the media is currently loaded.

(my emphasis) See also HTMLVideoElement and HTMLMediaElement.currentTime.

So:

const videoNote = document.querySelector("video");
videoNote.pause();
videoNote.currentTime = 0;

Upvotes: 2

Related Questions