Search code examples
javascripthtmldomvideoplayback

Why can't my video play?


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();
}
};
  • thanks

Solution

  • 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>