Unpredictable result

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="robots" content="noindex, nofollow">
</head>

<body>
    <div class="video_bg">
        <div class="video_wrap">
            <video id="videot" poster="media/videoframe.png" loop autoplay muted>
                <source type="video/webm" src="media/videoframe.webm">
                <source type="video/mp4" src="media/videoframe.mp4">
            </video>
        </div>
    </div>

    <script>
        var myVideo = document.getElementById('videot');
        document.addEventListener("DOMContentLoaded", function() {
            alert(String(myVideo.duration) + " seconds");
        });
    </script>
</body></html>

ALERT result – NAN seconds –

I upload this HTML one through the local server (Open Server)…
But when testing through Chrome DevTools, the correct result is shown…

where is the mistake ???

Is the videot element loaded dynamically?
What’s the HTML surrounding this?

I revised my message

I would probably use a different event… canplay or loadeddata

what is bad about this event ???

The DomContentLoaded event occurs when the HTML tags have all been loaded, and before all of the content such as images or videos have been accessed.

If you want the video duration, you may have to use the document load event instead, when the browser has had time to load the video.

There are also other video-specific events that could be used too so that you can get the information earlier than on load completed.

2 Likes