Search code examples
javascripthtml5-videodom-eventsevent-delegation

How to add onplay event to all html5 videos that are added dynamically to the page?


I am trying the following code for adding onplay event to all the videos that are added dynamically to my page but it is not working!

I tried with jQuery event-delegation but still not working, but I would prefer pure JavaScript solution.

 document.addEventListener('play', function(e){
  console.log("video started");
 })

 document.addEventListener('play', function(e){
      console.log("video started");
 })
<video width="400" controls>
  <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4">
  Your browser does not support HTML5 video.
</video>


Solution

  • I found a solution, I need to pass the 3rd parameter as true.

    e.g.

     document.addEventListener('play', function(e){
      console.log("video started");
     }, true);