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

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 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>

Toogle icon (play/pause), and stop when another button is clicked

Hope this post is not doubled, since i've search a lot for my same question and i surely found some but none of them really helped me.
I just need to 'mix' the scripts i found so i get what i need, let me explain better with my code:
Script for play a song and stop when another is clicked (but no pause if i click the same button)
var currentsound;
function play_pause(player) {
if(currentsound)
{
currentsound.pause();
}
var myAudio = document.getElementById(player);
myAudio.play();
currentsound = myAudio;
myAudio.currentTime = 0;
}
And this is another script i found here for toogle the icon :
var play = false;
function toggle() {
var image = document.getElementById('image')
var scan = document.getElementById('scan');
play = !play;
if (play) {
image.src = "pause.png";
scan.play();
}
else {
image.src = "play.png";
scan.pause();
}
}
HTML PART:
<audio preload="none" id="myAudio2" src="rosina2.mp3" type="audio/mpeg"> </audio>
<img src="play.png" width=30 height=30 border="0"
onclick="play_pause('myAudio2')" id="image">
</p></td>
<td width="29%" class="bonuspointstyle11"><p align="center"> 2 </p></td>
<td width="58%" class="bonuspointstyle11"><p class="bonuspointstyle5"> Istanpitta</p></td>
</tr>
<tr>
<td width="13%" class="bonuspointstyle11"><p>
<center>
<audio preload="none" id="myAudio3" src="rosina3.mp3" type="audio/mpeg"> </audio>
<img src="play.png" onclick="play_pause('myAudio3')"; width=30 height=30 border="0" >
</center>
</p></td>
<td width="29%" class="bonuspointstyle11"><p align="center"> 3 </p></td>
<td width="58%" class="bonuspointstyle11"><p class="bonuspointstyle5"> Gaetta </p></td>
</tr>
<tr>
<td width="13%" class="bonuspointstyle11"><p>
<center>
<audio preload="none" id="myAudio4" src="rosina2.mp3" type="audio/mpeg"> </audio>
<img src="play.png" onclick="play_pause('myAudio4')"; width=30 height=30 border="0" >
</center>
</p></td>
<td width="29%" class="bonuspointstyle11"><p align="center"> 4 </p></td>
<td width="58%" class="bonuspointstyle11"><p class="bonuspointstyle5">TEST </p></td>
</tr>
Im looking to get a simple play/pause button that toggle when clicked (to play image to pause image of course) and if any other button is clicked the last one gets stopped and start to sound the new one.
How can i toggle for more than once? In the answer i've got 1 which envolve calling the fuction i have but it's the same as only the first button toggle (even when i clicked on any other button)
Edit: Even if anybody can tell me how to make a script for only toggling any amount of buttons you have indiviually, i'd be grateful
I'd really really appreciate any kind of comment/advice that lead me to get my code running as i want. Thanks
Best regards
I suppose your first code is wrong:
var currentsound;
function play_pause(player) {
if (currentsound) {
currentsound.pause();
currentsound = null; // currentsound should be reset and return from functions to prevent playing again
return;
}
var myAudio = document.getElementById(player);
myAudio.play();
currentsound = myAudio;
myAudio.currentTime = 0;
//myAudio.play(); // duplicated code
}
To toggle an image it's not nessasary to mix the code. Just call the second functions from first one with some modifications:
function toggleIcon(playing) {
var image = document.getElementById('image')
if (playing) {
image.src = "play.png";
} else {
image.src = "pause.png";
}
}
And call it from first function:
function play_pause(player) {
if (currentsound) {
currentsound.pause();
currentsound = null;
toggleIcon(false); // <----- toggleIcon false
return;
}
var myAudio = document.getElementById(player);
myAudio.play();
currentsound = myAudio;
myAudio.currentTime = 0;
toggleIcon(true); // <----- toggleIcon true
}
Or even better - use events pause and play and do not touch play_pause function:
document.getElementById("myAudio2").onpause = function() {
toggleIcon(false);
};
document.getElementById("myAudio2").onplay = function() {
toggleIcon(true);
};
Well, after a lot of research i could get something that for now it's ok for me.
I just want to share if anybody else gets my same problem
This are my scripts (i needed to use 2)
<script language="javascript">
var currentsound;
function play_pause(player) {
var myAudio = document.getElementById(player);
if(myAudio.paused) {
myAudio.play();
} else{
myAudio.pause();
}
}
function changeImage(img) {
var imgfile = img.src.split(/\s+/).pop();
if (imgfile =="http://www.../.../pause.png" )
{
img.src = "http://www.../.../play.png";
}
else
{
img.src = "http://www.../.../pause.png";
}
}
</script>
And what basically do is that the first function do a play/pause for each button, and 2nd function toggle the image (see the onclick event)
This is my HTML:
<audio preload="none" id="myAudio1" src="http://www.../.../Music1.mp3" type="audio/mpeg"> </audio>
<img src="http://www.../.../play.png" width=30 height=30 border="0"
onclick="play_pause('myAudio1');changeImage(this)"> <!--id needs to be changed manually (id and onclick event) -->
<audio preload="none" id="myAudio2" src="http://www.../.../Music2.mp3" type="audio/mpeg"> </audio>
<img src="http://www.../.../play.png" width=30 height=30 border="0"
onclick="play_pause('myAudio2');changeImage(this)">
Indeed is not the best solution, because every time you click on another button (different from the one is running) them both will sound at same time, but at least you can play/pause each button individually and toggle the icons too.
For more button just copy-paste the html part and change the id part
Hope is usefull for anyone else than me, and if you got a better answer like having a counter variable for put into the ID so don't need to be changed manually or playing/pause and stopping when any other button gets click, post it, will be very appreciate it!
Regards
Use this script like this so you can toggle images and stop the audio also
<script>
function audios1(img,player) {
var image = document.getElementById(img);
var audio = document.getElementById(player);
var otherimage = document.getElementsByTagName('img');
for(var i = 0, len = otherimage.length; i < len;i++){
if(otherimage[i] != image){
otherimage[i].src= "start4.png";
}
}
if (image.src.match("start4.png")) {
image.src = "stop.png";
audio.play();
} else {
image.src = "start4.png";
audio.pause();
}
audio.addEventListener("ended", function() {
audio.currentTime = 0;
image.src = "start4.png";
});
}
function audios2(img,player) {
var image = document.getElementById(img);
var audio = document.getElementById(player);
var otherimage = document.getElementsByTagName('img');
for(var i = 0, len = otherimage.length; i < len;i++){
if(otherimage[i] != image){
otherimage[i].src= "start4.png";
}
}
if (image.src.match("start4.png")) {
image.src = "stop.png";
audio.play();
} else {
image.src = "start4.png";
audio.pause();
}
audio.addEventListener("ended", function() {
audio.currentTime = 0;
image.src = "start4.png";
});
}
document.addEventListener('play', function(e){
var audios = document.getElementsByTagName('audio');
for(var i = 0, len = audios.length; i < len;i++){
if(audios[i] != e.target){
audios[i].pause();
audios[i].currentTime = 0;
}
}
},true);
</script>

HTML5 video addEventListener 'ended' not fired

I have made a video slider that cycles trough video's. I tested the code several time when I was working on it, but a week later when I set the content online it did not function anymore.
What the problem is:
Firefox > Works fine, the addEventListener gets called and all is well
Chrome > Works fine, no errors but the addEventListener is not called and the cycle is not continued.
Is this a common Chrome bug, or did I bug my own code?
The cycle that I have created is this>
/* SLIDER */
var counter = 0;
var vid_count = 2;
var logotime = 2000;
var waittime = 5000;
function mainRotation(index){
loadVideo(index);
}
function loadVideo(index){
var video = document.getElementById('slideVideo' + index);
if(video.getAttribute("src")==null) {
video.setAttribute("src", './templates/tacticalghillies/video/slidevideo_' + index + '.mp4');
video.load();
}
else{
video.currentTime = 0;
$('#slideVideo' + index).show();
}
$('#slideImage').addClass('fadeout');
var timing = setInterval(function(){
showVideo(index, function(){
if(counter < vid_count-1){
counter++;
mainRotation(counter);
}
else{
mainRotation(counter);
counter = 0;
}
});
clearInterval(timing);
}, waittime)
}
function showVideo(index, cb){
//fade in video opacity
//play video
//video ended:
var video = document.getElementById('slideVideo' + index);
video.play();
console.log("playing");
video.addEventListener('ended', myHandler, false);
function myHandler(e){
if(!e) { e = window.event; }
console.log("eddd");
$('#slideImage').removeClass('fadeout');
var timer = setInterval(function() {
clearInterval(timer);
$('#slideVideo' + index).hide();
cb();
}, logotime);
}
}
Just to be clear this is the HTML that corrosponds with this piece of code:
<div class="animation">
<img class="a_aligned" id="slideImage" src="./images/slide_holder.png">
<video class="a_aligned slideVideo" width="1280" style="max-width:1280px;" id="slideVideo0" ></video>
<video class="a_aligned slideVideo" width="1280" style="max-width:1280px;" id="slideVideo1" ></video>
<img class="a_aligned" style="z-index:-1;" src="./images/slide_overlay.png">
</div>
Exactly same problem here... Didn't find yet how to solve this situation.
For information, this exactly same code was working well yesterday. It happend when I updated Chrome to the version 38.0.2125.104
Actually my exact code is :
$(videoBack).on("ended", function(){ [...]
Edit: Because I had a demo to do, I have use a quick fix, but I still have to figure why Chrome doesn't take the ended event anymore.
Quick fix:
setTimeout(function(){ [...] }, 1400);

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