[javascript] Detect if HTML5 Video element is playing

I've looked through a couple of questions to find out if an HTML5 element is playing, but can't find the answer. I've looked at the W3 documentation and it has an event named "playing" but I can't seem to get it to work.

This is my current code:

var stream = document.getElementsByTagName('video');

function pauseStream() {
  if (stream.playing) {
    for (var i = 0; i < stream.length; i++) {
      stream[i].pause();
      $("body > header").addClass("paused_note");
      $(".paused_note").text("Stream Paused");
      $('.paused_note').css("opacity", "1");
    }
  }
}

This question is related to javascript html video html5-video dom-events

The answer is


I just added that to the media object manually

let media = document.querySelector('.my-video');
media.isplaying = false;

...

if(media.isplaying) //do something

Then just toggle it when i hit play or pause.


jQuery(document).on('click', 'video', function(){
        if (this.paused) {
            this.play();
        } else {
            this.pause();
        }
});

a bit example when playing video

  let v = document.getElementById('video-plan');
  v.onplay = function() {
      console.log('Start video')
  };

My requirement was to click on the video and pause if it was playing or play if it was paused. This worked for me.

<video id="myVideo" #elem width="320" height="176" autoplay (click)="playIfPaused(elem)">
  <source src="your source" type="video/mp4">
</video>

inside app.component.ts

playIfPaused(file){
    file.paused ? file.play(): file.pause();
}

I encountered a similar problem where I was not able to add event listeners to the player until after it had already started playing, so @Diode's method unfortunately would not work. My solution was check if the player's "paused" property was set to true or not. This works because "paused" is set to true even before the video ever starts playing and after it ends, not just when a user has clicked "pause".


Best approach:

function playPauseThisVideo(this_video_id) {

  var this_video = document.getElementById(this_video_id);

  if (this_video.paused) {

    console.log("VIDEO IS PAUSED");

  } else {

    console.log("VIDEO IS PLAYING");

  }

}

a bit example

_x000D_
_x000D_
var audio = new Audio('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3')_x000D_
_x000D_
if (audio.paused) {_x000D_
  audio.play()_x000D_
} else {_x000D_
  audio.pause()_x000D_
}
_x000D_
_x000D_
_x000D_


Add eventlisteners to your media element. Possible events that can be triggered are: Audio and video media events

_x000D_
_x000D_
<!DOCTYPE html> _x000D_
<html> _x000D_
<head>  _x000D_
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> _x000D_
<title>Html5 media events</title>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
</head> _x000D_
<body >_x000D_
    <div id="output"></div>_x000D_
    <video id="myVideo" width="320" height="176" controls autoplay>_x000D_
        <source src="http://www.w3schools.com/tags/mov_bbb.mp4" type="video/mp4">_x000D_
        <source src="http://www.w3schools.com/tags/mov_bbb.ogg" type="video/ogg">_x000D_
    </video>_x000D_
    <script>_x000D_
        var media = document.getElementById('myVideo');_x000D_
_x000D_
        // Playing event_x000D_
        media.addEventListener("playing", function() {_x000D_
            $("#output").html("Playing event triggered");_x000D_
        });_x000D_
   _x000D_
        // Pause event_x000D_
        media.addEventListener("pause", function() { _x000D_
            $("#output").html("Pause event triggered"); _x000D_
        });_x000D_
_x000D_
        // Seeking event_x000D_
        media.addEventListener("seeking", function() { _x000D_
            $("#output").html("Seeking event triggered"); _x000D_
        });_x000D_
_x000D_
        // Volume changed event_x000D_
        media.addEventListener("volumechange", function(e) { _x000D_
            $("#output").html("Volumechange event triggered"); _x000D_
        });_x000D_
_x000D_
    </script>   _x000D_
</body> _x000D_
</html>
_x000D_
_x000D_
_x000D_


This is my code - by calling the function play() the video plays or pauses and the button image is changed.

By calling the function volume() the volume is turned on/off and the button image also changes.

function play() { 
  var video = document.getElementById('slidevideo'); 
  if (video.paused) {
    video.play()
    play_img.src = 'img/pause.png'; 
  }
  else {
    video.pause()
    play_img.src = 'img/play.png';
  }
}

function volume() { 
  var video = document.getElementById('slidevideo');
  var img = document.getElementById('volume_img');
  if (video.volume > 0) {
    video.volume = 0
    volume_img.src = 'img/volume_off.png';  
  }
  else {
    video.volume = 1
    volume_img.src = 'img/volume_on.png';
  }
}

I just did it very simply using onpause and onplay properties of the html video tag. Create some javascript function to toggle a global variable so that the page knows the status of the video for other functions.

Javascript below:

   // onPause function
   function videoPause() {
      videoPlaying = 0;
   }

   // onPause function
   function videoPlay() {
      videoPlaying = 1;
   }

Html video tag:

<video id="mainVideo" width="660" controls onplay="videoPlay();" onpause="videoPause();" >
                             <source src="video/myvideo.mp4" type="video/mp4">

                            </video>

than you can use onclick javascript to do something depending on the status variable in this case videoPlaying.

hope this helps...


Here is what we are using at http://www.develop.com/webcasts to keep people from accidentally leaving the page while a video is playing or paused.

$(document).ready(function() {

    var video = $("video#webcast_video");
    if (video.length <= 0) {
        return;
    }

    window.onbeforeunload = function () {
        var htmlVideo = video[0];
        if (htmlVideo.currentTime < 0.01 || htmlVideo.ended) {
            return null;
        }

        return "Leaving this page will stop your video.";
    };
}

I just looked at the link @tracevipin added (http://www.w3.org/2010/05/video/mediaevents.html), and I saw a property named "paused".

I have ust tested it and it works just fine.


My answer at How to tell if a <video> element is currently playing?:

MediaElement does not have a property that tells about if its playing or not. But you could define a custom property for it.

Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
    get: function(){
        return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
    }
})

Now you can use it on video or audio elements like this:

if(document.querySelector('video').playing){
    // Do anything you want to
}

var video_switch  = 0;

function play() {

    var media = document.getElementById('video');

    if (video_switch == 0)
    {
        media.play();
        video_switch = 1;
    }
    else if (video_switch == 1)
    {
        media.pause();
        video_switch = 0;
    }
}

It seems to me like you could just check for !stream.paused.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

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 html5-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? In Chrome 55, prevent showing Download button for HTML 5 video HTML 5 Video "autoplay" not automatically starting in CHROME How to open .mov format video in HTML video Tag? What is a blob URL and why it is used? .mp4 file not playing in chrome HTML5 video won't play in Chrome only use video as background for div HTML5 Video tag not working in Safari , iPhone and iPad Video 100% width and height

Examples related to dom-events

Detecting real time window size changes in Angular 4 Does Enter key trigger a click event? What are passive event listeners? Stop mouse event propagation React onClick function fires on render How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over iFrame onload JavaScript event addEventListener, "change" and option selection Automatically pass $event with ng-click? JavaScript click event listener on class