239

I am trying to control HTML5 videos using JQuery. I have two clips in a tabbed interface, there are six tabs in total, the others just have images. I am trying to make the video clips play when their tab is clicked and then stop when any of the others are clicked.

This must be a simple thing to do but I cant seem to get it to work, the code I am using to play the video is:

$('#playMovie1').click(function(){
  $('#movie1').play();
      });

I have read that the video element needs to be exposed in a function to be able to control it but can't find an example. I am able to make it work using JS:

document.getElementById('movie1').play();

Any advice would be great. Thanks

Barny83
  • 2,395
  • 2
  • 14
  • 4

18 Answers18

399

Your solution shows the issue here -- play is not a jQuery function but a function of the DOM element. You therefore need to call it upon the DOM element. You give an example of how to do this with the native DOM functions. The jQuery equivalent -- if you wanted to do this to fit in with an existing jQuery selection -- would be $('#videoId').get(0).play(). (get gets the native DOM element from the jQuery selection.)

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • 7
    That's great, works perfectly, thanks indeed. Good to understand the DOM better also. – Barny83 Jan 10 '11 at 15:39
  • 1
    Using JQuery to control video in this way seems to cause problems with playback on the iPhone. I have the video element in a tab, the jquery reveals this, but then clicking on the video start arrow does not start the clip. When I remove the $('#videoId').get(0).play() line there is no problem. What is the best way around this? I was thinking I could remove the js with a condtional statement for iOS - the video will not autostart for iOS devices anyway so would be happy to do this - or is there a simpler solution? Any help much appreciated. – Barny83 Mar 03 '11 at 15:59
  • How can I make this pause *all* the – prismspecs Nov 20 '12 at 19:30
  • @prismspecs $("video").get(0).play() – russellsayshi Apr 28 '13 at 21:05
  • 8
    @russellsayshi - no, that will only play ONE video; prismspecs asked for ALL videos. Correct syntax: `$('video').each(this.play());` to play all; `$('video').each(this.pause());` to pause all. `each()` is a jQuery function, what is passed into it is a javascript function, that is applied to each element. As each element is handled, `this` represents that element. – ToolmakerSteve Aug 15 '14 at 02:21
  • 12
    If only want the first element, can simplify by replacing `.get(0)` with `[0]`. So `$('video')[0].play();` or for a specific id `$('#videoId')[0].play();`. – ToolmakerSteve Aug 15 '14 at 02:25
  • @Barny83 - did you end up figuring out a solution to the iPhone related issue? –  Sep 14 '16 at 16:44
  • urm... and what if the element doesn't exist – Simon_Weaver Apr 23 '17 at 21:09
98

You can do

$('video').trigger('play');
$('video').trigger('pause');
plowman
  • 13,335
  • 8
  • 53
  • 53
wonder
  • 1,001
  • 7
  • 2
58

This is how I managed to make it work:

jQuery( document ).ready(function($) {
    $('.myHTMLvideo').click(function() {
        this.paused ? this.play() : this.pause();
    });
});

All my HTML5 tags have the class 'myHTMLvideo'

Lumbendil
  • 2,906
  • 1
  • 19
  • 24
Miguel Tavares
  • 715
  • 6
  • 10
  • 7
    Note that there's no need to wrap in jQuery so you can save that overhead by replacing the ternary line with this: `this.paused ? this.play() : this.pause();` – Pete Watts May 09 '14 at 07:27
27

Why do you need to use jQuery? Your proposed solution works, and it's probably faster than constructing a jQuery object.

document.getElementById('videoId').play();
isherwood
  • 58,414
  • 16
  • 114
  • 157
sudo work
  • 778
  • 5
  • 10
  • Check out lonesomeday's solution if you insist on a jQuery implementation (also for an explanation of why you can't just call `play` on a jQuery object). – sudo work Jan 10 '11 at 13:10
  • I was thinking I would use the code within other jQuery, and probably will do so, but as it stands I am just using that line so I guess it could have been done with the code I had... also I wasn't sure if that was good practice to mix. Thanks for the advice anyway. – Barny83 Jan 10 '11 at 15:40
  • 2
    If you've already instantiated a jQuery object for `movie1` through `$('movie1')` for other jQuery actions, then it's fine; however, if you're doing it just in this one place, you're going to find some performance loss. It may not be noticeable enough, but I like to optimize a lot. – sudo work Jan 11 '11 at 01:52
  • @sudowork - seriously? you're discussing performance loss when starting a video playing? If your device is fast enough to play video, it is fast enough to do a barrel of jQuery actions without user noticing. – ToolmakerSteve Aug 15 '14 at 02:30
23

For pausing multiple videos I have found that this works nicely:

$("video").each(function(){
    $(this).get(0).pause();
});

This can be put into a click function which is quite handy.

MKB
  • 7,587
  • 9
  • 45
  • 71
Josh Holmes
  • 231
  • 2
  • 2
  • 5
    You can do the same like so: $("video").each(function(){ this.pause() }); – Marcel M. Apr 22 '14 at 17:43
  • 1
    $(this) -> you create jquery object from "this" object. get(0) -> you get back the original "this" object from jquery object... this === $(this).get(0) – Blackfire Aug 21 '17 at 11:28
15

As an extension of lonesomeday's answer, you can also use

$('#playMovie1').click(function(){
    $('#movie1')[0].play();
});

Notice that there is no get() or eq() jQuery function called. DOM's array used to call play() function. It's a shortcut to keep in mind.

ozanmuyes
  • 721
  • 12
  • 26
14

I like this one:

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

Hope it helps.

8

This is the easy methods we can use

on jquery button click function

$("#button").click(function(event){
    $('video').trigger('play');
    $('video').trigger('pause');
}

Thanks

subindas pm
  • 2,668
  • 25
  • 18
5

I use FancyBox and jQuery to embedd a video. Give it an ID.

Perhaps not the BEST solution could toggle play/pause differently - but easy for me and IT WORKS! :)

In the

`

<input type="hidden" id="current_video_playing">

<input type="hidden" id="current_video_status" value="playing">

<video id="video-1523" autobuffer="false" src="movie.mp4"></video>

<script>

// Play Pause with spacebar

$(document).keypress(function(e) { 

    theVideo = document.getElementById('current_video_playing').value

    if (e.which == 32) {

        if (document.getElementById('current_video_status').value == 'playing') {

            document.getElementById(theVideo).pause();

            document.getElementById('current_video_status').value = 'paused'

        } else {

            document.getElementById('current_video_status').value = 'playing'

            document.getElementById(theVideo).play();

        }

    }

});

</script>`
Alexander W
  • 51
  • 1
  • 1
3

Found the answer here @ToolmakerSteve, but had to fine tune this way: To pause all

$('video').each(function(index){
    $(this).get(0).pause();
});

or to play all

$('video').each(function(index){
    $(this).get(0).play();
});
2

By JQuery using selectors

$("video_selector").trigger('play');  
$("video_selector").trigger('pause');
$("div.video:first").trigger('play');$("div.video:first").trigger('pause');
$("#video_ID").trigger('play');$("#video_ID").trigger('pause');

By Javascript using ID

video_ID.play();  video_ID.pause();

OR

document.getElementById('video_ID').play();  document.getElementById('video_ID').pause();
Riyaz Hameed
  • 1,087
  • 12
  • 10
1

Just as a note, make sure you check if the browser supports the video function, before you try to invoke it:

if($('#movie1')[0].play)
    $('#movie1')[0].play();

That will prevent JavaScript errors on browsers that don't support the video tag.

Alex W
  • 37,233
  • 13
  • 109
  • 109
1

var vid = document.getElementById("myVideo"); 
function playVid() { 
  vid.play(); 
} 
function pauseVid() { 
  vid.pause(); 
} 
<video id="myVideo" width="320" height="176">
  <source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
  <source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.ogg" type="video/ogg">
  Your browser does not support HTML5 video.
</video>
<button onclick="playVid()" type="button">Play Video</button>
<button onclick="pauseVid()" type="button">Pause Video</button><br> 
1

use this.. $('#video1').attr({'autoplay':'true'});

Antares500
  • 27
  • 1
  • 2
    "I am trying to make the video clips play when their tab is clicked" - so an event controlled handling is needed. – davidenke Feb 18 '15 at 11:43
0

I also made it work like this:

$(window).scroll(function() {
    if($(window).scrollTop() > 0)
        document.querySelector('#video').pause();
    else
        document.querySelector('#video').play();
});
MKB
  • 7,587
  • 9
  • 45
  • 71
Jasper Chang
  • 50
  • 2
  • 7
0

@loneSomeday explained it beautifully , here one solution which might also give you good idea how to achieve play/pause functionality

play/pause of video on click

Community
  • 1
  • 1
Sheelpriy
  • 1,675
  • 17
  • 28
0
<video style="min-width: 100%; min-height: 100%; " id="vid" width="auto" height="auto" controls autoplay="true" loop="loop" preload="auto" muted="muted">
<source src="video/sample.mp4" type="video/mp4">
<source src="video/sample.ogg" type="video/ogg">
</video>
<script> 
$(document).ready(function(){
document.getElementById('vid').play(); });
</script> 
Anusuya
  • 11
0
    enter code here
<form class="md-form" action="#">
  <div class="file-field">
    <div class="btn btn-primary btn-sm float-left">
      <span>Choose files</span>
      <input type="file" multiple>
    </div>
    <div class="file-path-wrapper">
      <input class="file-path validate" type="text" placeholder="Upload one or more files">
    </div>
  </div>
</form>

<video  width="320" height="240" id="keerthan"></video>

<button onclick="playVid()" type="button">Play Video</button>
<button onclick="pauseVid()" type="button">Pause Video</button> 
<script>
    (function localFileVideoPlayer() {

  var playSelectedFile = function (event) {
    var file = this.files[0]
    var type = file.type
    var videoNode = document.querySelector('video')




    var fileURL = URL.createObjectURL(file)
    videoNode.src = fileURL
  }
  var inputNode = document.querySelector('input')
  inputNode.addEventListener('change', playSelectedFile, false)
})()
function playVid() { 
  keerthan.play(); 
} 

function pauseVid() { 
  keerthan.pause(); 
} 

</script>
  • Hi, welcome to Stack Overflow. When answering a question that already has many answers, please be sure to add some additional insight into why the response you're providing is substantive and not simply echoing what's already been vetted by the original poster. This is especially important in "code-only" answers such as the one you've provided. – chb Mar 19 '19 at 08:23