muted does not work for dynamically created videos - javascript

I created a plugin that dynamically creates video tags with src
plugin.js
(function($)
{
$.fn.Video = function(props)
{
$(this).html('');
var src = $(this).data('src');
var source = $('<source />', {src: src, type: 'video/mp4'});
var obj = {'controls': ''};
if(props != undefined)
{
if('muted' in props)
{
console.log('\t muted on');
var muted = props['muted']
if(muted == true)
{
obj['muted'] = '';
}
}
}
var video = $('<video />', obj);
video.css({'width': '100%'});
video.append(source);
video.append('Your browser does not support the video tag');
$(this).append(video);
return this;
};
}(jQuery));
example
<div class="video" data-src="http://video.archives.org/video.mp4"></div>
$('.video').Video({muted: True});
This is how the video is rendered
<div class="video" data-src="http://video.archives.org/video.mp4">
<video controls="controls" muted="" style="width: 100%;">
<source src="http://video.archives.org/video.mp4" type="video/mp4">Your browser does not support the video tag
</video>
</div>
The problem is that muted does not work when the video is dynamically created. How can I fix this ?

well the way you are setting the muted property it will not work because
attributes are only used to initialize the properties. They do not reflect the current state.
try chaining the statements instead and then set the attribute/property on video.
(function($) {
$.fn.Video = function(props) {
$(this).html('');
var src = $(this).data('src');
var source = $('<source />', {
src: src,
type: 'video/mp4'
});
var obj = {
'controls': ''
};
if (props != undefined) {
if ('muted' in props) {
console.log('\t muted on');
var muted = props['muted']
if (muted == true) {
obj.muted = 'muted';
}
}
}
var video = $('<video />', {
controls: true
}).prop('muted', muted);
video.css({
'width': '100%'
});
video.append(source);
video.append('Your browser does not support the video tag');
$(this).append(video);
return this;
};
}(jQuery));
$('.video').Video({
muted: true
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="video" data-src="https://www.w3schools.com/tags/movie.mp4"></div>

Related

I want to play each button for each video in pure JS

I have a page where I have multiple videos I created one custom button to play video
The problem is I want to write a single JS to achieve this without writing multiple js code for each video
<video id="video"> </video>
<button id="circle-play-b">play</button
<video id="video"> </video>
<button id="circle-play-b">play</button
JS
var video = document.getElementById("video");
var circlePlayButton = document.getElementById("circle-play-b");
console.log(video);
function togglePlay() {
if (video.paused || video.ended) {
video.play();
} else {
video.pause();
}
}
circlePlayButton.addEventListener("click", togglePlay);
video.addEventListener("playing", function () {
circlePlayButton.style.opacity = 0;
});
video.addEventListener("pause", function () {
circlePlayButton.style.opacity = 1;
});
I have an option to add unique id to each video
You have to set seperate listeners for each video elements.And use class names instead of id.
document.getElementByClassName returns array of elements. Iterates over array and set listeners for each elements.
Html
<video class="videos"> </video>
<button class="circle-play-b">play</button>
<video class="videos"> </video>
<button class="circle-play-b">play</button>
Js
var videos = document.getElementsByClassName("videos");
var circlePlayButton = document.getElementsByClassName("circle-play-b");
for (let i = 0; i < circlePlayButton.length; i++) {
let playBtn = circlePlayButton[i];
let video = videos[i];
function togglePlay() {
if (video.paused || video.ended) {
video.play();
} else {
video.pause();
}
}
playBtn.addEventListener('click', togglePlay);
video.addEventListener("playing", function () {
playBtn.style.opacity = 0;
});
video.addEventListener("pause", function () {
playBtn.style.opacity = 1;
});
}
Hope it helps to solve your issue
A valid approach was to treat the video and button structure as a reusable component.
Thus one would provide a generically written (no equally named id attributes) closed html structure ( <video/> and <button/> elements are embedded within a parent or root element).
Then one would implement an initializing function which queries such HTML structures/components and registers every event handler needed.
Of cause any handler and helper function is implemented (and named) in a way that it targets exactly one problem/task a time ( ... which enables code-reuse as shown with the next provided example code) ...
function getToggleControl(elmVideo) {
return elmVideo
.closest('figure')
.querySelector('button');
}
function updateToggleControl(toggleControl, isPaused) {
const { dataset } = toggleControl;
const controlText = isPaused
? dataset.textTogglePlay
: dataset.textTogglePause;
toggleControl.textContent = controlText;
toggleControl.title = controlText;
}
function handleToggleState({ currentTarget: toggleControl }) {
const elmVideo = toggleControl
.closest('figure')
.querySelector('video');
if (elmVideo) {
const isPaused = elmVideo.paused || elmVideo.ended;
if (isPaused) {
elmVideo.play();
} else {
elmVideo.pause();
}
updateToggleControl(toggleControl, !isPaused);
}
}
function handleVideoPlaying({ currentTarget: elmVideo }) {
const toggleControl = getToggleControl(elmVideo);
if (toggleControl) {
toggleControl.style.opacity = .2;
updateToggleControl(toggleControl, false);
}
}
function handleVideoPaused({ currentTarget: elmVideo }) {
const toggleControl = getToggleControl(elmVideo);
if (toggleControl) {
// initially enable the video pause/play button.
toggleControl.disabled && (toggleControl.disabled = false);
toggleControl.style.opacity = 1;
updateToggleControl(toggleControl, true);
}
}
function initVideoPausePlay() {
document
.querySelectorAll('figure[data-video-pause-play] video')
.forEach(elmVideo => {
elmVideo.addEventListener('canplay', handleVideoPaused);
elmVideo.addEventListener('pause', handleVideoPaused);
elmVideo.addEventListener('playing', handleVideoPlaying);
getToggleControl(elmVideo)
?.addEventListener('click', handleToggleState);
});
}
initVideoPausePlay();
* { margin: 0; padding: 0; }
figure { display: inline-block; width: 40%; }
figure video { display: inline-block; width: 100%; }
<figure data-video-pause-play>
<video controls muted>
<source src="https://ia902803.us.archive.org/15/items/nwmbc-Lorem_ipsum_video_-_Dummy_video_for_your_website/Lorem_ipsum_video_-_Dummy_video_for_your_website.mp4" type="video/mp4">
<source src="https://archive.org/embed/nwmbc-Lorem_ipsum_video_-_Dummy_video_for_your_website/Lorem_ipsum_video_-_Dummy_video_for_your_website.HD.mov" type="video/quicktime">
</video>
<button
disabled
class="circle-play-b"
data-text-toggle-play="play"
data-text-toggle-pause="pause">
...
</button>
</figure>
<figure data-video-pause-play>
<video controls muted>
<source src="https://ia902803.us.archive.org/15/items/nwmbc-Lorem_ipsum_video_-_Dummy_video_for_your_website/Lorem_ipsum_video_-_Dummy_video_for_your_website.mp4" type="video/mp4">
<source src="https://archive.org/embed/nwmbc-Lorem_ipsum_video_-_Dummy_video_for_your_website/Lorem_ipsum_video_-_Dummy_video_for_your_website.HD.mov" type="video/quicktime">
</video>
<button
disabled
class="circle-play-b"
data-text-toggle-play="play"
data-text-toggle-pause="pause">
...
</button>
</figure>

how to play multiple mediaelementplayer one by one in javascript

I have three videos shown on the website:
<video id="player0" class="video-player" muted preload="metadata"...>....</video>
<video id="player1" class="video-player" muted preload="metadata"...>....</video>
<video id="player2" class="video-player" muted preload="metadata"...>....</video>
and in my javascript, I have:
$(document).ready(function() {
$('.video-player').mediaelementplayer({
alwaysShowControls:true,
videoVolume: 'vertical',
features: ['playpause','current','progress','duration','tracks','volume','fullscreen','mobileautomute'],
success: function (mediaElement, domObject) {
var target = document.body.querySelectorAll('.video-player');
for (a=0;a<target.length;a++){
target[a].style.visibility = 'visible';
}
mediaElement.addEventListener('loadedmetadata', function() {
mediaElement.play();
}, false);
}
});
});
With this code, all three videos load together and it random pick one video to autoplay, and cannot go to another one to play automatically.
How can I make all three videos all loaded at first time, but play one by one in video 0 to video 1 then video 2?
Thanks.
I figure it how to fix my problem:
changed all the preload form metadata to none, as below
<video id="player0" class="video-player" muted preload="metadata"...>....</video>
to
<video id="player0" class="video-player" muted preload="none"...>....</video>
Revised the javascript to below:
$(document).ready(function() {
$('.video-player').mediaelementplayer ({
pauseOtherPlayers: true,
alwaysShowControls:true,
videoVolume: 'vertical',
autoplay: true,
features: ['playpause','current','progress','duration','tracks','volume','fullscreen','mobileautomute'],
success: function (mediaElement, domObject) {
var target = document.body.querySelectorAll('.video-player');
for (a=0;a<target.length;a++){
target[a].style.visibility = 'visible';
}
var theID = mediaElement['attributes']['id'].value;
if (theID == "player0"){
mediaElement.play();
mediaElement.addEventListener('ended', function() {
var videoElem = document.getElementById("player1");
videoElem.play();
});
} else if (theID == "player1"){
mediaElement.addEventListener('ended', function() {
var videoElem = document.getElementById("player2");
videoElem.play();
});
}
}
});
});

How to know if a video from <iframe> is playing (youtube AND vimeo)

I have an iframe of youtube / vimeo content and I would know if the video is playing when my function is executed.
Actually, when someone click on an image, my code set the right video corresponding at this image in the iframe. and i have a button which pause and hide my iframe
I found this with youtube API: getPlayerState() ,
and getPaused() from vimeo API.
I don't want to use click event, I would like to be able to know the pauseState at everytime !
https://developers.google.com/youtube/iframe_api_reference?hl=fr
https://developer.vimeo.com/player/sdk/reference#events-for-text-tracks
<iframe id="player" class="center" width="560" height="315" src="" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<script src="https://player.vimeo.com/api/player.js"></script>
<script src="https://www.youtube.com/iframe_api"></script>
function loadVideo(id) {
var videoPlayer = document.getElementById('videoPlayer');
var player = document.getElementById('player');
var url = player.src;
switch (id) {
case 1:
url = "https://www.youtube.com/embed/n1tswFfg-Ig?enablejsapi=1";
break ;
case 2:
url = "https://player.vimeo.com/video/237596019?api=1";
break ;
default:
callPlayer("pauseVideo");
break ;
function callPlayer(func, args) {
var iframes = document.getElementsByTagName('iframe');
for (var i = 0; i < iframes.length; ++i) {
if (iframes[i]) {
var src = iframes[i].getAttribute('src');
if (src) {
if (src.indexOf('youtube.com/embed') != -1) {
var player = new YT.Player(iframes[i], {});
//2 lines below doesn't work
var value = player.getPlayerState();
alert('value');
iframes[i].contentWindow.postMessage(JSON.stringify({
'event': 'command',
'func': func,
'args': args || []
}), "*");
}
if (src.indexOf('player.vimeo.com/video') != -1) {
var player = new Vimeo.Player(iframes[i]);
switch (func) {
case 'pauseVideo':
//always show 'false', never 'true'
if (player.getPaused() == true ) {
alert('true');
}else {
alert('false');
}
player.pause();
break ;
default:
break ;
}
}
}
}
}
}
i use alert to know if something is working, and with this code, the youtube alert does not work , and the vimeo alert always show 'false'.
Thanks for your help
Maybe the issue can be related to the use of the same iframe, which ends up messing up the functions of each type of video. In this way, a solution would be to use more than one iframe that would be displayed or hidden as needed.
Another problem that has been reported is that starting the YouTube video directly through <iframe> does not end up activating the listening functions. So, the ideal is to follow as recommended in the YouTube Player API documentation and start the video with a <div>, so that .getPlayerState() and other methods work well.
// Buttons to switch videos
function changeVideo (btn) {
if (btn.classList.contains("active")) {
return;
}
document.querySelector('.buttons .active').classList.remove('active');
document.querySelector('.video .active').classList.remove('active');
document.querySelector("." + btn.dataset.video + "-video").classList.add('active');
btn.classList.add('active');
}
// YouTube starter
let youtubePlayer;
function onYouTubeIframeAPIReady() {
youtubeVideo = new YT.Player('youtubePlayer', {
height: '315',
width: '560',
videoId: 'tgbNymZ7vqY'
});
}
// YouTube - check if it's paused
function checkYoutubePaused() {
let state = youtubeVideo.getPlayerState();
if (state <= 0 || state == 2 || state == 5) {
return true;
}
return false;
}
// Vimeo starter
const vimeoIframe = document.querySelector('.vimeo-video');
const vimeoPlayer = new Vimeo.Player(vimeoIframe);
// Vimeo - check if it's paused
async function checkVimeoPaused() {
let state;
await vimeoPlayer.getPaused().then(function(paused) {
state = paused;
});
return state;
}
// My Function
async function myFunction() {
vimeoState = await checkVimeoPaused();
let youtubePaused = checkYoutubePaused() ? "PAUSED" : "RUNNING";
let vimeoPaused = vimeoState ? "PAUSED" : "RUNNING";
alert("Youtube Video is " + youtubePaused + "\n" + "Vimeo Video is " + vimeoPaused);
}
.youtube-video {
display: none;
}
.vimeo-video {
display: none;
}
.video .active {
display: inline;
}
.buttons .active {
color: #ffffff;
background-color: #333333;
}
<script src="https://player.vimeo.com/api/player.js"></script>
<script src="https://www.youtube.com/iframe_api"></script>
<div class="video">
<div id="youtubePlayer" class="youtube-video active"></div>
<iframe class="vimeo-video" src="https://player.vimeo.com/video/120680495" width="560" height="315" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
<div>
<span class="buttons">
<button data-video="youtube" class="active" onclick="changeVideo(this)">Youtube Video</button>
<button data-video="vimeo" onclick="changeVideo(this)">Vimeo Video</button>
</span>
<span>
<button onclick="myFunction()">Run My Function</button>
</span>
</div>

TextTrackList onchange event not working in IE and Edge

The TextTrackList.onchange event is not working in IE and Edge. In Chrome and FireFox it works fine.
Is there any alternative I can use? Ive searched through the available events but can't find any.
Or how can I create a workaround? So it works amongst all browsers?
https://www.javascripture.com/TextTrackList
var video = document.getElementById('video');
video.textTracks.addEventListener('change', function () {
console.log("TextTracks change event fired!");
});
video {
max-width: 400px;
max-height: 400px;
}
<video controls id="video">
<source src="https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_30mb.mp4" type="video/mp4" />
<track label="Caption #1" kind="subtitles" srclang="nl" src="path/to/caption1.vtt">
<track label="Caption #2" kind="subtitles" srclang="en" src="path/to/caption2.vtt">
<track label="Caption #3" kind="subtitles" srclang="de" src="path/to/caption3.vtt">
</video>
You might be able to create a kind of polyfill.
First to detect if we support the event or not, we can check for ('onchange' in window.TextTrackList). So we can integrate our unperfect polyfill conditionally and leave the correct implementations unchanged.
Then, we can iterate every x-time over our TextTrackList's TextTracks in order to find which one is the active one, it should be the one with its mode set to "showing".
Now, we just have to store the previous active track and check if the current one is the same. Otherwise, fire the Event.
So a simple implementation could be
// in an outer scope
// textTracks is our TextTrackList object
var active = getActive();
// start polling
poll();
function poll() {
// schedule next check in a frame
requestAnimationFrame(poll);
var current = getActive();
if (current !== active) {
active = current; // update the active one
// dispatchEvent is not supported on TextTrackList in IE...
onchange({
target: textTracks
});
}
}
function getActive() {
for (var i = 0; i < textTracks.length; i++) {
if (textTracks[i].mode === 'showing') {
return textTracks[i];
}
}
}
But to implement a better polyfill, we will want to override the original addEventListener, removeEventListener and onchange properties of the TextTrackList prototype.
Here is a rough implementation, which will not take care of the third param of [add/remove]EventListener.
(function() {
/* Tries to implement an 'change' Event on TextTrackList Objects when not implemented */
if (window.TextTrackList && !('onchange' in window.TextTrackList.prototype)) {
var textTracksLists = [], // we will store all the TextTrackLists instances
polling = false; // and run only one polling loop
var proto = TextTrackList.prototype,
original_addEvent = proto.addEventListener,
original_removeEvent = proto.removeEventListener;
var onchange = {
get: getonchange,
set: setonchange
};
Object.defineProperty(proto, 'onchange', onchange);
Object.defineProperty(proto, 'addEventListener', fnGetter(addListener));
Object.defineProperty(proto, 'removeEventListener', fnGetter(removeListener));
function fnGetter(fn) {
return {
get: function() {
return fn;
}
};
}
/* When we add a new EventListener, we attach a new object on our instance
This object set as '._fakeevent' will hold informations about
the current EventListeners
the current onchange handler
the parent <video> element if any
the current activeTrack
*/
function initFakeEvent(instance) {
// first try to grab the video element from where we were generated
// this is useful to not run useless tests when the video is detached
var vid_elems = document.querySelectorAll('video'),
vid_elem = null;
for (var i = 0; i < vid_elems.length; i++) {
if (vid_elems[i].textTracks === instance) {
vid_elem = vid_elems[i];
break;
}
}
textTracksLists.push(instance);
instance._fakeevent = {
parentElement: vid_elem,
listeners: {
change: []
}
}
if (!polling) { // if we are the first instance being initialised
polling = true;
requestAnimationFrame(poll); // start the checks
}
return instance._fakeevent;
}
function getonchange() {
var fakeevent = this._fakeevent;
if (!fakeevent || typeof fakeevent !== 'object') {
return null;
}
return fakeevent.onchange || null;
}
function setonchange(fn) {
var fakeevent = this._fakeevent;
if (!fakeevent) {
fakeevent = initFakeEvent(this);
}
if (fn === null) fakeevent.onchange = null;
if (typeof fn !== 'function') return fn;
return fakeevent.onchange = fn;
}
function addListener(type, fn, options) {
if (type !== 'change') { // we only handle change for now
return original_addEvent.bind(this)(type, fn, options);
}
if (!fn || typeof fn !== 'object' && typeof fn !== 'function') {
throw new TypeError('Argument 2 of EventTarget.addEventListener is not an object.');
}
var fakeevent = this._fakeevent;
if (!fakeevent) {
fakeevent = initFakeEvent(this);
}
if (typeof fn === 'object') {
if (typeof fn.handleEvent === 'function') {
fn = fn.handleEvent;
} else return;
}
// we don't handle options yet...
if (fakeevent.listeners[type].indexOf(fn) < 0) {
fakeevent.listeners[type].push(fn);
}
}
function removeListener(type, fn, options) {
if (type !== 'change') { // we only handle change for now
return original_removeEvent.call(this, arguments);
}
var fakeevent = this._fakeevent;
if (!fakeevent || !fn || typeof fn !== 'object' && typeof fn !== 'function') {
return
}
if (typeof fn === 'object') {
if (typeof fn.handleEvent === 'function') {
fn = fn.handleEvent;
} else return;
}
// we don't handle options yet...
var index = fakeevent.listeners[type].indexOf(fn);
if (index > -1) {
fakeevent.listeners[type].splice(index, 1);
}
}
function poll() {
requestAnimationFrame(poll);
textTracksLists.forEach(check);
}
function check(instance) {
var fakeevent = instance._fakeevent;
// if the parent vid not in screen, we probably have not changed
if (fakeevent.parentElement && !fakeevent.parentElement.parentElement) {
return;
}
// get the current active track
var current = getActiveTrack(instance);
// has changed
if (current !== fakeevent.active) {
if (instance.onchange) {
try {
instance.onchange({
type: 'change',
target: instance
});
} catch (e) {}
}
fakeevent.listeners.change.forEach(call, this);
}
fakeevent.active = current;
}
function getActiveTrack(textTracks) {
for (var i = 0; i < textTracks.length; i++) {
if (textTracks[i].mode === 'showing') {
return textTracks[i];
}
}
return null;
}
function call(fn) {
fn({
type: 'change',
target: this
});
}
}
})();
var video = document.getElementById('video');
video.textTracks.onchange = function ontrackchange(e) {
console.log('changed');
};
video {
max-width: 400px;
max-height: 400px;
}
<video controls id="video">
<source src="https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_30mb.mp4" type="video/mp4" />
<track label="Caption #1" kind="subtitles" srclang="nl" src="path/to/caption1.vtt">
<track label="Caption #2" kind="subtitles" srclang="en" src="path/to/caption2.vtt">
<track label="Caption #3" kind="subtitles" srclang="de" src="path/to/caption3.vtt">
</video>
You are correct, it is an issue with IE and Edge.
What you can do is listen to an event on the track load. Just pay attention that the track has got to be on the same domain, otherwise, you will get a silent error (CURS) and the event lister will not list the event.
I have created a code pan so you could try it https://codepen.io/shahar-polak/project/live/AnVpEw/
NOTE: The code will trigger one event in IE and Edge and two events on Chrome and Firefox. Make sure you check for the client browser before using in production.
const video = document.getElementById('video');
const tracks = Array.from(document.querySelectorAll('track'));
video.textTracks.addEventListener('change', function() {
console.log('TextTracks change event fired!');
});
// For IE and Edge
tracks.forEach((track) => {
track.addEventListener("load", function() {
console.log('change track');
}, false);
})
video {
max-width: 400px;
max-height: 400px;
}
<video controls id="video" >
<source src="https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_30mb.mp4" type="video/mp4"/>
<track label="Caption #1" kind="subtitles" srclang="nl" src="./en.vtt">
<track label="Caption #2" kind="subtitles" srclang="en" src="./en.vtt">
<track label="Caption #3" kind="subtitles" srclang="de" src="https://iandevlin.com/html5/dynamic-track/captions/sintel-en.vtt">
</video>

How to loop a video 3 times only?

I want to loop a video three times only. Rendering it in a for loop doesn't seem to work properly.
I am wondering how to do this with an HTML video.
I have this HTML video.
<div id="video" class="Adform-video"></div>
And this JS
(function() {
Floating.setup({
clicktag: dhtml.getVar('clickTAG', 'http://example.com'),
target: dhtml.getVar('landingPageTarget', '_blank'),
video: {
sources: dhtml.getVar('videoSources'),
poster: dhtml.getAsset(3),
clicktag: dhtml.getVar('clickTAG')
}
});
Floating.init();
})();
var Floating = (function() {
var videoPlayer;
var banner = dhtml.byId('banner'),
closeButton = dhtml.byId('closeButton'),
video = dhtml.byId('video'),
clickArea = dhtml.byId('click-area'),
lib = Adform.RMB.lib;
function setup(settings) {
for (var prop in settings) {
if (_settings[prop] instanceof Object) {
for (var prop2 in settings[prop]) {
_settings[prop][prop2] = settings[prop][prop2];
}
} else {
_settings[prop] = settings[prop];
}
}
}
var _settings = {
clicktag: null,
target: null,
video: null
};
function init() {
createVideoPlayer();
}
closeButton.onclick = function (event) {
dhtml.external.close && dhtml.external.close();
};
clickArea.onclick = function() {
stopVideo();
window.open(_settings.clicktag, _settings.target);
};
function createVideoPlayer() {
var videoSettings = _settings.video;
videoPlayer = Adform.Component.VideoPlayer.create({
sources: videoSettings.sources,
clicktag: videoSettings.clicktag,
loop: videoSettings.loop,
muted: videoSettings.muted,
poster: videoSettings.poster,
theme: 'v2'
});
if (videoPlayer) {
videoPlayer.removeClass('adform-video-container');
videoPlayer.addClass('video-container');
videoPlayer.appendTo(video);
}
function landPoster() {
if(!lib.isWinPhone) {
videoPlayer.video.stop();
}
}
videoPlayer.poster.node().onclick = landPoster;
if (lib.isAndroid && lib.isFF) {
lib.addEvent(video, 'click', function(){}, false);
}
}
function stopVideo() {
if (videoPlayer.video.state === 'playing') videoPlayer.video.pause();
}
return {
setup: setup,
init: init
};
})();
The video will be used as an ad, and therefore I will only loop through it trice.
I have looked at these posts but they didn't seem to work:
Loop HTML5 video
Prop video loop
How can I do that?
Check out the standard HTML5 video element's onended event handler. Set up a simple JS event function with a integer counter and use the pause feature of video element when counter reaches 3. This link should help!
https://www.w3schools.com/TAGS/av_event_ended.asp
Also, I'm curious to know why exactly you want a video to loop only thrice...
Anyway, if the functionality is somewhat similar to a small animation(of a small video) which should be played 3 times, consider making a GIF animation with three hard-coded repetitions!
PROBLEM SOLVED
<!DOCTYPE html>
<html>
<body>
<video id="myVideo" width="320" height="176" autoplay controls>
<source src="mov_bbb.mp4" type="video/mp4">
<source src="mov_bbb.ogg" type="video/ogg">
Your browser does not support the audio element.
</video>
<script>
var aud = document.getElementById("myVideo");
var a=0;
aud.onended = function() {
a=a+1;
if(a!=3)
{
aud.play();
}
};
</script>
</body>
</html>

Categories

Resources