DFD
DFD

Reputation: 37

HTML5 play pause video on image or video click

I have an HTML5 Video on my page without controls. I use an image over the video (a play icon). I want that the video can play/pause on click over the video or over the icon image.

This is the script I've tried to use but doesn't work:

If I click over the video it works fine, meanwhile if I click on the icon image nothing happens.

$(document).on('click', 'video', '#btnplay', function (e) {
        var video = $(this).get(0);
        if (video.paused === false) {
            video.pause();
            } else {
            video.play();
        }
        return false;
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="video-container">
  <video autoplay="autoplay" loop="loop" width="100%" height="auto" class="videohome"> Your browser does not support the video tag. <source src="images/video/video.mp4" type="video/mp4" /></video>
  <img id="btnplay" class="playbtn" src="images/play.png" alt="Play">
</div>

Any suggestion? Thanks in advance.

Upvotes: 0

Views: 2366

Answers (1)

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

$(document).on('click', 'video, #btnplay', function (e) {
        var video = $('video').get(0);  // This line has been updated.
        if (video.paused === false) {
            video.pause();
            } else {
            video.play();
        }
        return false;
    });

Explanation: There are two changes needed, the two selectors in one inverted comma, and although we click on any of them, get the 'video' element for reference, so instead of $(this).get(0) I changed it to $('video').get(0) so either we click on the icon or click on video tag itself, it always refers to the video tag only.

Upvotes: 2

Related Questions