Search code examples
jqueryhtmlvideo

How to stop (not pause) html5 video with jQuery


I have a page that plays a short clip from a video (full video isn't supposed to be available on this page) using the html5 video tag. If a user visits the page and navigates back, when they visit a second time (within several minutes), the video doesn't play. I believe it is because I am using jQuery to pause the video after 7 seconds:

$('#playButton').click(function(event){
$('#theVideo').get(0).play()    
setTimeout(function(){$('#theVideo').get(0).pause() }, 7000);
});

I tried using .stop() as suggested in the unaccepted answer on this question: Make HTML5 video stop at indicated time

This code does not work:

// doesn't work
setTimeout(function(){$('#theVideo').get(0).stop()  }, 7000);
// also doesn't work
setTimeout(function(){$('#theVideo').stop() }, 7000);

I've referenced Mozilla's documentation. The only quasi-official documentation I've found for jQuery and HTML5 video is from w3schools: https://www.w3schools.com/tags/ref_av_dom.asp

It does not reference a "stop" method. Should I expect .stop() to work, or do I need to find another solution?

My video code:

<video playsinline id='theVideo' poster=''>
<source src='http://somedomain/subfolder/playlist.m3u8'>
</video>
<div id="playButton">PLAY</div>

I appreciate your help.


Solution

  • There is no .stop(). You just can pause it...

    But you also can set the currentTime back to zero (begining of the file)...
    That will be nice to have it ready to play again on subsequent #playButton click.

    That would be:

    $('#playButton').click(function(event){
      $('#theVideo').get(0).play(); 
      setTimeout(function(){
        $('#theVideo').get(0).pause();
        $('#theVideo').get(0).currentTime = 0;
      }, 7000);
    });
    

    Now, «If a user visits the page and navigates back»... Holà!! Using the browser's back button? Nothing you can do here. The JavaScript is not ran like a normal page load here. Nothing can happen "on back".