how to play multiple mediaelementplayer one by one in javascript - 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();
});
}
}
});
});

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>

muted does not work for dynamically created videos

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>

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>

fullpage.js video end image show for every section

I am trying to hide the video at the end and show up the image but its reloading every time. I tried all the possible way and i am very new with js.
here is my code
<script type="text/javascript">
$(document).ready(function() {
$('#fullpage').fullpage({
navigation: true,
navigationPosition: 'right',
verticalCentered: true,
onLeave: function(index, nextIndex, direction){
//var img = document.getElementById("myImg");
var vid = document.getElementById("myVideo");
//var vidup = document.getElementById("yourVideo");
//var hide = document.getElementsById('yourVideo')[0].style.visibility = 'visible';
if(direction ==='down'){
$('video').each(function () {
//playing the video
$(this).get(0).play();
});
}
else if(direction ==='up'){
$('video').each(function () {
//playing the video
$(this).get(0).play();
});
}
},//onLeave END
afterRender: function () {
$('video').each(function () {
//playing the video
$(this).get(0).play();
});
}
});
});
</script>
I need help to load image after the video and evertime i comeback to the slide the video should autoplay and show the image at the end.

html5 video can't play after pause

I am struggling with the auto pause and then play(manual) again issue.The video is pausing after 2 seconds which is fine. Now there is another button and on click that button the video should start playing from the position it was paused.
Here is my code(html):
<div class="restart">Restart after pause</div>
<video id="video" width="400" height="400" id="video" src="http://media.w3.org/2010/05/sintel/trailer.mp4" controls autoplay />
jquery:
jQuery(document).ready(function ($) {
$('#video').get(0).play();
setInterval(function () {
if ($('#video').get(0).currentTime >= 2) {
$('#video').get(0).pause();
}
}, 100);
$(".restart").click(function(event){
$('#video').get(0).play();
setInterval(function () {
if ($('#video').get(0).currentTime >= 6) {
$('#video').get(0).pause();
}
}, 100);
});
});
I am definitely not on the right path regarding current time and set time.Please suggest.
The JSFiddle is
http://jsfiddle.net/squidraj/KmQxL/10/
Thanks in advance.
Please review this fiddle: http://jsfiddle.net/VZuuF/1/
I got rid of your setIntervals as they are unneccessary with the timeupdate event available.
$(document).ready(function()
{
var checkedFirst = false;
var checkedSecond = false;
$player = $('#video').get(0);
$player.play();
$player.addEventListener('timeupdate', function(event)
{
console.log($player.currentTime);
if ($player.currentTime >= 2 && !checkedFirst)
{
checkedFirst = true;
$player.pause();
}
if ($player.currentTime >= 6 && !checkedSecond)
{
checkedSecond = true;
$player.pause();
}
});
$(".restart").click(function(event)
{
$player.play();
});
});

Categories

Resources