Reputation: 128
I'm trying to display "duration" for each video on the page using JavaScript. here is what I've come up with so far:
var vid = document.querySelector(".mhdividdur");
vid.onloadedmetadata = function() {
var x = document.querySelector(".mhdividdur").duration;
document.querySelector(".mhdi_video_duration").innerHTML = x;
};
<video class="mhdividdur" width="240px" controls preload="metadata" poster="http://cdn1.ko.cowa.ir//kocofeaturedimage.jpg">
<source src="http://cdn1.ko.cowa.ir//hwasa.mp4" type='video/mp4'>
</video>
<p class="mhdi_video_duration"></p>
<video class="mhdividdur" width="240px" controls preload="metadata" poster="http://cdn1.ko.cowa.ir//kocofeaturedimage.jpg">
<source src="http://cdn1.ko.cowa.ir//numb.mp4" type='video/mp4'>
</video>
<p class="mhdi_video_duration"></p>
The problem is that it only returns the duration for the 1st video.
What should I do?
P.S. If there are any other ways except JavaScript to display duration, please give me a hint.
Thank You all
Upvotes: 2
Views: 513
Reputation: 1382
with querySelector
function you can get the first of the elements that match the selector you entered. that's why you need to get all the video elements with querySelectorAll
function which will return an array of elements and loop to print their duration.
var videos = document.querySelectorAll(".mhdividdur");
var durationsEl = document.querySelectorAll(".mhdi_video_duration");
for(let i = 0; i < videos.length; i++) {
videos[i].onloadedmetadata = function() {
durationsEl[i].innerHTML = videos[i].duration;
};
}
<video class="mhdividdur" width="240px" controls preload="metadata" poster="http://cdn1.ko.cowa.ir//kocofeaturedimage.jpg">
<source src="http://cdn1.ko.cowa.ir//hwasa.mp4" type='video/mp4'>
</video>
<p class="mhdi_video_duration"></p>
<video class="mhdividdur" width="240px" controls preload="metadata" poster="http://cdn1.ko.cowa.ir//kocofeaturedimage.jpg">
<source src="http://cdn1.ko.cowa.ir//numb.mp4" type='video/mp4'>
</video>
<p class="mhdi_video_duration"></p>
Upvotes: 3