Search code examples
javascriptjqueryhtmlhtml5-videoplayback

JQuery play html5 video starting from second zero but preserving the current frame if the user pause the video


I have a problem with native html5 videos that I would like to customize with a poster taken from a video frame. So I decided that all my videos will have queued the parameter #t=1 that tells the browser to start the video from the second 1 onwards. In this way I have the possibility to have a poster in my video instead of a black background. But I have a problem that simplifies as follows... with the following JQuery code I tell the browser to re-initialize the video from the second 0 instead of the second 1, this because I have in my videos #t=1. So with this JQuery code I partly solved the problem, because I have the video poster, the video although set to start after the second 1 starts from second 0 but here arises a problem, the user clicks on the video, puts it on pause but always starts from second 0, but I would rather that in case the user pauses the video, this starts from the point where it was interrupted and not from the beginning.

Here is my pseudo code...

$(document).ready(function() {
  var video = $("video")[0];
  // video starting from #t=1 now play from #t=0
  $("video").on("play", function() {
    this.currentTime = 0;
  });
  // pseudo code...
  if pause video then continue from interruption
});

Every suggestion is appreciated. Thank you.

$(document).ready(function() {
  var video = $("video")[0];
  $("video").on("play", function() {
    this.currentTime = 0;
   }); 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="video-html5" style="float: left; margin: 0 5px 5px 0"><video width="560" height="315" controls preload="metadata"><source src="https://archive.org/download/ElephantsDream/ed_1024_512kb.mp4#t=1" type="video/mp4"></video></div>


Solution

  • $("video").one( would solve your problem as you asked it, but I agree with commenters, you'd probably be better to use directly the poster attribute rather than this hack.

    $(document).ready(function() {
      $("video").one("play", function() {
        this.currentTime = 0;
       }); 
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="video-html5" style="float: left; margin: 0 5px 5px 0"><video width="560" height="315" controls preload="metadata"><source src="https://archive.org/download/ElephantsDream/ed_1024_512kb.mp4#t=1" type="video/mp4"></video></div>