Reputation: 1801
This is getting pretty frustrating. I make a video and willing to play it in js [with no jquery]. And everytime, it fail. The console said play is not defined
. Can you help me please
<video id='video'>
<source src='http://techslides.com/demos/sample-videos/small.mp4' type='video/mp4'>
<source src='http://techslides.com/demos/sample-videos/small.ogv' type='video/ogg'>
<embed src='http://techslides.com/demos/sample-videos/small.flv' type='x-shockwave-flash'>
</video>
<button onclick='play()' >Play/Pause</button>
.
window.onload = function() {
var video = document.getElementById('video');
if (video.paused) {
video.play();
} else {
video.pause();
}
};
Upvotes: 0
Views: 642
Reputation: 7949
Your function to play or pause should be separate from the document loading:
window.playPause = function () {
var myVideo = document.getElementById('video');
if (myVideo.paused) {
myVideo.play();
} else {
myVideo.pause();
}
};
...then, hook that up to your button:
<button onclick='playPause()'>Play/Pause</button>
This works for me with the video you're using. If you want the video to autoplay when the document loads (which isn't really a good idea) you should indicate that in the tag rather than the JavaScript:
<video id='video' autoplay>
Upvotes: 1
Reputation: 422
You are calling the play method on the button. For the onClick event instead of just calling play, call the video element's play method.
<button onclick="video.play();">Play/Pause</button>
Upvotes: 0