John Abraham
John Abraham

Reputation: 18791

How would I make a playTo() function in jquery for html5 video

Question: How can I contruct my playTo() function to take a value and play to that value as a timestamp of the video? The video will play until that timestamp is hit; afterwhich video will be paused.

HTML:

<video src="assets/trailer.mp4" class="video" controls muted>
  Your browser does not support the <code>video</code> element.
</video>
<button class="next-chapter">next chapter</button>

JS:

var vid = $('.video')[0];
var play = $('.next-chapter');

//this controlls which index of timestamp
var sceneCounter = 0;

//these are the timestampes
var timestamps = [10,20,30,40];

//this function will play the video normally
var playVideo = function() {
  vid.play();
};

//heres what I plan to set the next timestamp
var playTo = function(t){
  //help here!!
  console.log('heyhey');
};

var nextScene = function() {
  sceneCounter++
};

$( play ).click(function() {
  if(sceneCounter !== 0){
    nextScene();  
  }
  playTo(sceneCounter);
});

vid.addEventListener('timeupdate',function(event){
  time = vid.currentTime;
  console.log(time);
},false);

Upvotes: 1

Views: 215

Answers (1)

Dhiraj
Dhiraj

Reputation: 33618

All you need is a .play() method and .pause() method.

var vid = $('.video')[0];
var play = $('.next-chapter');

//this controlls which index of timestamp
var sceneCounter = -1;

//these are the timestampes
var timestamps = [2,4,6,8];

//this function will play the video normally
var playVideo = function() {
  vid.play();
};

//heres what I plan to set the next timestamp
var playTo = function(t){
  //help here!!
    vid.play();
};

var nextScene = function() {
  sceneCounter++;
};

$(play).click(function() {
  if(sceneCounter != timestamps.length-1){
    nextScene();  
    playTo(sceneCounter);
  }
});

vid.addEventListener('timeupdate',function(event){
    if(vid.currentTime >= timestamps[sceneCounter]){
        vid.pause();
    }
},false);
html {padding: 20px 0; background-color: #efefef;}
body {width: 400px; padding: 40px; margin: 0 auto; background: #fff; box-shadow: 1px 1px 5px rgba(0,0,0,0.5);}

video {
    width: 400px; 
    display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" class="video" controls muted>
  Your browser does not support the <code>video</code> element.
</video>
<button class="next-chapter">next chapter</button>
<!--
<source id="mp4" src="" type="video/mp4">
-->

Hope this helps.

Upvotes: 1

Related Questions