Clicking HTML 5 Video element to play, pause video, breaks play button

I'm trying to get the video to be able to play and pause like it does YouTube (Using both the play and pause button, and clicking the video itself.)

<video width="600" height="409" id="videoPlayer" controls="controls">
 <!-- MP4 Video -->
 <source src="video.mp4" type="video/mp4">
</video>


<script>
    var videoPlayer = document.getElementById('videoPlayer');

    // Auto play, half volume.
    videoPlayer.play()
    videoPlayer.volume = 0.5;

    // Play / pause.
    videoPlayer.addEventListener('click', function () {
        if (videoPlayer.paused == false) {
            videoPlayer.pause();
            videoPlayer.firstChild.nodeValue = 'Play';
        } else {
            videoPlayer.play();
            videoPlayer.firstChild.nodeValue = 'Pause';
        }
    });
</script>

Do you have any ideas why this would break the play and pause control button?


Solution 1:

The simplest form is to use the onclick listener:

<video height="auto" controls="controls" preload="none" onclick="this.play()">
 <source type="video/mp4" src="vid.mp4">
</video>

No jQuery or complicated Javascript code needed.

Play/Pause can be done with onclick="this.paused ? this.play() : this.pause();".

Demo:

<video height="200" controls="controls" preload="none" onclick="this.play()">
 <source type="video/webm" src="https://upload.wikimedia.org/wikipedia/commons/transcoded/5/54/Yawning_kitten.ogv/Yawning_kitten.ogv.480p.vp9.webm">
</video>

On Chromium 89:

  • onclick="this.play()" prevents the video from playing again by clicking on the body (rather than controls) after an initial play + pause (clicking on controls still works), which is generally undesirable. This is presumably because the callback makes it play, and then the event propagates and the browser immediately re-pauses it.
  • the default behavior without onclick="this.play()" would be: initial body click to play on body does not work, but after initial play clicks on body do toggle play/pause
  • onclick="this.paused ? this.play() : this.pause();" makes body clicks after the initial play not work neither to play nor pause, presumably for an analogous to what happens with onclick="this.play()"

Solution 2:

HTML:

<video class="video"><source src=""></video>

JAVASCRIPT: "JQUERY"

$('.video').click(function(){this.paused?this.play():this.pause();});

Solution 3:

Adding return false; worked for me:

jQuery version:

$(document).on('click', '#video-id', function (e) {
    var video = $(this).get(0);
    if (video.paused === false) {
        video.pause();
    } else {
        video.play();
    }

    return false;
});

Vanilla JavaScript version:

var v = document.getElementById('videoid');
v.addEventListener(
    'play', 
    function() { 
        v.play();
    }, 
    false);

v.onclick = function() {
    if (v.paused) {
        v.play();
    } else {
        v.pause();
    }

    return false;
};