11

I have a HTML code like this:

... <video id="abc" preload="auto" autoplay="autoplay" loop="loop" webkit-playsinline="">
    <source src="3.mp4" type="video/mp4">
</video> ...

And I used this JS code:

$(document).ready(function () {
"use strict";


    $("#abc").load(function () {
        console.log(3);
    });
});

I wanna run that function when the video loads. The JS code works with img tag but not with video tag. I want it to work like the img tag. Like I want it not to run when it loads videos from cache.
How can I do that?

M.M.M.M.
  • 113
  • 1
  • 1
  • 4

2 Answers2

16

HTML element video does not have load event. It has others, like loadstart, loadeddata or loadedmetadata. See a full list of possible viedo events here.

$("#abc").on("loadstart", function() {
  console.log(3);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<video id="abc" preload="auto" autoplay="autoplay" loop="loop" webkit-playsinline="">
  <source src="https://www.quirksmode.org/html5/videos/big_buck_bunny.mp4" type="video/mp4">
</video>

loadeddata: Fires when the browser has loaded the current frame of the audio/video
loadedmetadata: Fires when the browser has loaded meta data for the audio/video
loadstart: Fires when the browser starts looking for the audio/video

eisbehr
  • 12,243
  • 7
  • 38
  • 63
  • How about the cache thing? How can I run the function only when the browser doesn't use cache? – M.M.M.M. Jun 24 '16 at 11:52
  • Even from cache it fires the events. I would not know a solution for an event, only triggered on first load. I'm sorry. But why is this even needed? – eisbehr Jun 24 '16 at 12:14
  • Does anyone know if loadstart definitely runs before "onerror"? https://www.w3schools.com/tags/av_event_error.asp – xaunlopez Aug 26 '20 at 01:53
2

You must use the loadeddata event to know when the video is loaded, you can see all properties of the event here:

loadeddata event

And an example here:

var video = document.getElementById("abc");
video.onloadeddata = function() {
     alert("Browser has loaded the current frame");
};

you can use jquery selectors too.

Mikel
  • 175
  • 1
  • 14
  • How does it work with cache? Does it run the function when the browser uses cache? – M.M.M.M. Jun 24 '16 at 12:04
  • You can try it here: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_av_event_loadeddata . i haven't found problems with cache – Mikel Jun 24 '16 at 12:33