[html] 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?

This question is related to html video youtube

The answer is


Following up on ios-lizard's idea:

I found out that the controls on the video are about 35 pixels. This is what I did:

$(this).on("click", function(event) {
    console.log("clicked");
    var offset = $(this).offset();
    var height = $(this).height();
    var y = (event.pageY - offset.top - height) * -1;
    if (y > 35) {
        this.paused ? this.play() : this.pause();
    }
});

Basically, it finds the position of the click relative to the element. I multiplied it by -1 to make it positive. If the value was greater than 35 (the height of the controls) that means that the user click somewhere else than the controls Therefore we pause or play the video.


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;
};

I had countless issues doing this but finally came up with a solution that works.

Basically the code below is adding a click handler to the video but ignoring all the clicks on the lower part (0.82 is arbitrary but seems to work on all sizes).

    $("video").click(function(e){

        // get click position 
        var clickY = (e.pageY - $(this).offset().top);
        var height = parseFloat( $(this).height() );

        // avoids interference with controls
        if(y > 0.82*height) return;

        // toggles play / pause
        this.paused ? this.play() : this.pause();

    });

How about this one

<video class="play-video" muted onclick="this.paused?this.play():this.pause();">
   <source src="" type="video/mp4">
</video>

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();".


must separate this code to work well, or it well pause and play in one click !

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

Not to bring up an old post but I landed on this question in my search for the same solution. I ended up coming up with something of my own. Figured I'd contribute.

HTML:

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

JAVASCRIPT: "JQUERY"

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

I had this same problem and solved it by adding an event handler for the play action in addition to the click action. I hide the controls while playing to avoid the pause button issue.

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

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

Seeking still acts funny though, but at least the confusion with the play control is gone. Hope this helps.

Anyone have a solution to that?


The problem appears to be internal bubbling within the <video> element ... so when you click on the "Play" button the code triggers and then the play button itself get triggered :(

I couldn't find a simple (reliable) way to stop the click bubbling through (logic tells me there should be a way, but... it escapes me right now)

Anyway, the solution I found to this was to put a transparent <div> over the video sized to fit down to where the controls appear... so if you click on the div then your script controls play/pause but if the user clicks on the controls themselves then the <video> element handles that for you.

The sample below was sized for my video so you may need to juggle sizes of the relative <div>s but it should get you started

<div id="vOverlay" style="position:relative; width:600px; height:300px; z-index:2;"></div>
<video style="position:relative; top:-300px; z-index:1;width:600px;height:340px;" width="600" height="409" id=videoPlayer controls="controls">
<source src="video.mp4" type="video/mp4">
</video>

<script>
    var v = document.getElementById('videoPlayer');
    var vv = document.getElementById('vOverlay');
    <!-- Auto play, Half volume -->
    v.play()
    v.volume = 0.5;
    v.firstChild.nodeValue = "Play";

    <!-- Play, Pause -->
    vv.addEventListener('click',function(e){
        if (!v.paused) {
            console.log("pause playback");
            v.pause();
            v.firstChild.nodeValue = 'Pause';
        } else {
            console.log("start playback")
            v.play();
            v.firstChild.nodeValue = 'Play';
        }
      });
</script>

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to video

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66? How to make a movie out of images in python HTML5 Video autoplay on iPhone How do we download a blob url video Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM How to embed new Youtube's live video permanent URL? How to disable auto-play for local video in iframe Writing an mp4 video using python opencv How to extract 1 screenshot for a video with ffmpeg at a given time? Bootstrap 3 - Responsive mp4-video

Examples related to youtube

Youtube - downloading a playlist - youtube-dl YouTube Autoplay not working How to embed new Youtube's live video permanent URL? How do you use youtube-dl to download live streams (that are live)? How can I get the actual video URL of a YouTube live stream? YouTube: How to present embed video with sound muted ffprobe or avprobe not found. Please install one Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000 cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'