Accessing duration attribute of a video DOM object

Can you please let me know how I can access video’s duration. For some reason, I am getting NaN for the duration

Note: the current time works as expected
Thank you

The reason is that video should be fully loaded before the duration will be known. One of the possible solutions is to add eventListener for loadeddata:'loadeddata', function () {
        console.log("duration is ",;
    }, false);

Example -
Later one may remove this listener if it is not needed anymore.


@labris Thank you for your solution. Looking at your playground, I realized that I can use “oncanplaythrough” instead to get the duration

Do you think that would be more preferable since then no need for bookkeeping to delete the listener?

Another option is to use video.onloadeddata

Example -

I believe it will work a bit faster.
The order of events for the video element:

  1. loadstart
  2. durationchange
  3. loadedmetadata
  4. loadeddata
  5. progress
  6. canplay
  7. canplaythrough

@labris Huge thank you! I actually was looking for this order of the events

1 Like

By the way, video.ondurationchange will be even faster :slight_smile:
Example -