How to loop a video 3 times only? - javascript

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>

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();
});
}
}
});
});

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 loop video with javascript?

i have some videos source. I want to play it again when the last video is over. I tried this code below,but after the last ended it wont start from the beginning.
Here's my code below
HTML
<video id="myVideo" width="800" height="600" controls>
Your browser does not support HTML5 video.
</video>
JAVASCRIPT
<script>
var videoSource = new Array();
videoSource[0]='video/adsfsaf.mp4';
videoSource[1]='video/2.mp4';
videoSource[2]='video/1.mp4';
var videoCount = videoSource.length;
document.getElementById("myVideo").setAttribute("src",videoSource[0]);
function videoPlay(videoNum)
{
document.getElementById("myVideo").setAttribute("src",videoSource[videoNum]);
document.getElementById("myVideo").load();
document.getElementById("myVideo").play();
}
function videoBegin(videoNum)
{
document.getElementById("myVideo").setAttribute("src",videoSource[0]);
document.getElementById("myVideo").load();
document.getElementById("myVideo").play();
}
i = 0;
document.getElementById('myVideo').addEventListener('ended',myHandler,false);
function myHandler() {
i++;
if(i == (videoCount-1)){
// alert(i);
videoPlay(i);
}
else{
videoPlay(i);
}
}
</script
I found the solution.
function myHandler() {
i++;
if(i >= videoCount) i =0;
videoPlay(i);
}
Can't you use the "loop" attribute of the "video" element ?
W3School loop

Start youtube video on hover/mouseover

I'm trying to get youtube videos to start on hover. It will pause (not stop) when the user hovers over another video...
I am stuck on the hover command. Can someone help me work it out please?
The page has 16 videos, this is the working code from the jsfiddle that contains 3 videos as an example.
http://jsfiddle.net/sebwhite/gpJN4/
VIDEO:
<iframe id="player" width="385" height="230" src="http://www.youtube.com/embed/erDxb4IkgjM?rel=0&wmode=Opaque&enablejsapi=1;showinfo=0;controls=0" frameborder="0" allowfullscreen></iframe>
JAVASCRIPT:
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onStateChange': onPlayerStateChange
}
});
onYouTubeIframeAPIReady();
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
player1.pauseVideo();
player2.pauseVideo();
}
UPDATED FIDDLE
Try this:
var $$ = function(tagname) { return document.getElementsByTagName(tagname); }
function onYouTubeIframeAPIReady() {
var videos = $$('iframe'), // the iframes elements
players = [], // an array where we stock each videos youtube instances class
playingID = null; // stock the current playing video
for (var i = 0; i < videos.length; i++) // for each iframes
{
var currentIframeID = videos[i].id; // we get the iframe ID
players[currentIframeID] = new YT.Player(currentIframeID); // we stock in the array the instance
// note, the key of each array element will be the iframe ID
videos[i].onmouseover = function(e) { // assigning a callback for this event
if (playingID !== currentHoveredElement.id) {
players[playingID].stopVideo();
}
var currentHoveredElement = e.target;
if (playingID) // if a video is currently played
{
players[playingID].pauseVideo();
}
players[currentHoveredElement.id].playVideo();
playingID = currentHoveredElement.id;
};
}
}
onYouTubeIframeAPIReady();
Fiddle:
http://jsfiddle.net/gpJN4/3/

Categories

Resources