I have this.
window.addEventListener('load', () => {
document.getElementById('myVideo').play();
document.getElementById('myVideo').addEventListener('ended',myHandler,false);
function myHandler(e) {
// What you want to do after the event
swiffyslider.slide(document.getElementById('mySwiffyslider'), next = true);
setInterval(() => swiffyslider.slide(sliderElement), 4000);
}
let sliderElement = document.getElementById('mySwiffyslider');
const container = sliderElement.querySelector(".slider-container");
const infiniteScrollToFirstWhenOnLast = () => {
if (container.lastElementChild == container.querySelector('.slide-visible')) {
container.scroll({
left: 0,
behavior: "instant"
});
}
};
//Append the first slide as the last
container.appendChild(container.firstElementChild.cloneNode(true));
//Add an additional indicator button to keep counts correct
sliderElement.querySelector(".slider-indicators").appendChild(sliderElement.querySelector(".slider-indicators").lastElementChild.cloneNode(true));
swiffyslider.onSlideEnd(sliderElement, infiniteScrollToFirstWhenOnLast, 90);
});
It plays the video, but when slider gets to the end, video is stopped, at the end, doesn't replay, and slider goes on. I just want the video to play again when slider ends.
Related
Currently, the same video is only able to autoplay 1 time.
To reproduce: Click 1 svg play button, then click the X.
Then click the same svg play button a 2nd time.
You will find that the video does not autoplay.
How is that fixed in the code so that the same video can autoplay a 2nd time?
I would either be using autoplay, or player.playVideo(); to have the video play a 2nd time.
I'm not sure how it would work.
https://jsfiddle.net/2h7dgfe5/
const videoPlayer = (function makeVideoPlayer() {
const players = [];
const tag = document.createElement("script");
tag.src = "https://www.youtube.com/player_api";
const firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function createStopHandler(player) {
const stopButtons = document.querySelectorAll(".exit");
stopButtons.forEach(function stopButtonHandler(buttons) {
buttons.addEventListener("click", function buttonClickHandler() {
player.stopVideo();
});
});
}
function onPlayerReady(event) {
const player = event.target;
player.setVolume(100);
createStopHandler(player);
}
function addPlayer(video, settings) {
const defaults = {
height: 360,
host: "https://www.youtube-nocookie.com",
videoId: video.dataset.id,
width: 640
};
defaults.events = {
onReady: onPlayerReady
};
const playerOptions = combinePlayerOptions(defaults, settings);
const player = new YT.Player(video, playerOptions);
players.push(player);
return player;
}
return {
addPlayer
};
}());
const managePlayer = (function makeManagePlayer() {
const defaults = {
playerVars: {
autoplay: 1,
controls: 1,
disablekb: 1,
enablejsapi: 1,
fs: 0,
iv_load_policy: 3
}
};
The problem is coming from the way you init the player the first time. When the player is just created there is a onPlayerReady function that is being called. This function is not called on popup open a second time.
You need to keep references to the players and when popup is opened so you could find the player you want and do:
player.playVideo();
I see that you keep them here: const players = []; but you don't have access to this when you open the popup so you can't really call .playVideo().
I would invest some time into creating a structure that holds references for the player based on the popup so it would be something like:
const players = new Map();
// key can be anything you may use to relate:
// - HTML reference -> the element you click could be your key
// - string
// - other object
// - number
players.set(anyReasonableKey, playerInstance)
// then click handler would be something like this
function onPlayButtonClick(event) {
const key = event.target;
const p = players.get(key); // event target is the key, the play button.
// if there is no player
if(typeof player === "undefined"){
// the creation with autoplay option should handle fist start of video, because you need to wait for onPlayerReady event
makePlayer(key) // here you create it for the first time, and pass the key so you could do the following inside of the function:
// players.set(key, player)
} else {
p.playVideo(); // if player exists, just start playing video
}
}
playButton.addEventListener("click", onPlayButtonClick)
Or ... a bit easier way (but not preferrable) would be to re-create the player every time the user opens the popup, this way it will always autoplay based on your init config.
I've added buttons to the page that when you click on each one, it first unloads the howl object and changes the src, and then new music is played. But the problem is that after changing src twice, the script does not work a third time
What does the following code do:
The how object creates howling
When you hit any button that has .play-btn, the source of each button puts in ._src sound and new music is played
<script>
var musicSrc = "";
var sound = 0;
var musicId= 0;
var soundCurrentTime ,soundTime = 0;
var soundPercent = 0;
var playInterval;
sound = new Howl({
src: '/uploads/tracks/'+$('.content > .music-list-player:first-of-type .play-btn').attr('track-file'),
volume: 1,
html5: true,
xhr: {
method: 'POST',
},
format : 'mp3',
onload: function () {
$('.player-container').removeClass('load-track'); //'Remove Music Loading Animation
soundTime = sound.duration(); //'Get Full Sound Time
soundPercent = (soundCurrentTime * 100)/soundTime; //'Get now Percent Played
$('.full-time#full-time').html(secondsToHms(soundTime)); //'Show Full Music Time in left Time Box
},
onplay:function () {
$('.player-container').removeClass('load-track'); //'Remove Music Loading Animation
playInterval= setInterval(playProgress,100);
$('.play-btn[playing="1"]').attr('player-target','pause');
},
onend: function () {
$('.play-btn[playing="1"]').attr('player-target','play'); //'Show Play Button
$('.player-progress-bar').css('width','0%'); //'Reset Progress Bar
$('.current-time').html("00:00"); //Set Current Time to 00:00
clearInterval(playInterval);
},
onpause: function () {
$('.player-container').removeClass('load-track'); //'Remove Music Loading Animation
$('#progress'+musicId+', #progress').css('width',soundPercent+'%');
$('.current-time').html('00:00');
$('.current-time#current-time , #current-time-'+musicId).html(secondsToHms(soundCurrentTime));
clearInterval(playInterval);
},
onloop: function () {
playInterval = setInterval(playProgress,100);
}
});
$('.music-list-player .play-btn').on('click', function () { //'It happens by Click the list play Button
$('.player-container').addClass('load-track');
var playerBtnClass = '.'+this.className;
var playingStatus = $(this).attr('player-target') == 'pause' ? playingStatus = 0 : playingStatus = 1;
musicId = this.id;
musicSrc = $(this).attr('track-file');
if (playingStatus){ //'Play btn is playing
if (sound._src !== '/uploads/tracks/'+musicSrc){ //'Music's changed
sound.stop();
sound.unload();
console.log(sound);
sound._src = '/uploads/tracks/'+musicSrc;
sound.load();
$('.player-progress-bar').css('width','0%'); //'Reset Progress Bar
$('.player-container').addClass('load-track'); //'add Music Loading Animation
}
$('.player-artist-name').html($(playerBtnClass+"#"+musicId+" + .artist-name ").html());
$('.player-music-name').html($(playerBtnClass+"#"+musicId+" + .artist-name + .music-name ").html());
$(this).attr('player-target','pause');
$(playerBtnClass+":not(#"+musicId+")").attr('player-target','play');
$('#play-btn').attr('player-target','pause');
sound.play();
}
else{ //'Play btn is not playing
$(this).attr('player-target','play');
$('#play-btn').attr('player-target','play');
sound.pause();
}
});
i am working on a video player and on that video player i have a div called #caption, when i play the video i hide the div and when i pause the video i show the div. This all works fine. Now i added a small part of javascript that shows the div when i move the mouse and hides the div again if i stop moving the mouse with a timeout. This works fine as well. However, if i pause the video and i move the mouse the #caption also hides with the time out. How do i prevent this piece of javascript to fire when the player is in pause, so the #caption is always visible when the video is paused.
var video = $('#thevideo')[0];
video.addEventListener('pause', function () {
$('#caption').show();
})
video.addEventListener('playing', function () {
$('#caption').delay(2500).fadeOut();
})
var i = null;
$("#videoContainer").mousemove(function () {
clearTimeout(i);
$("#caption").fadeIn();
i = setTimeout(function () {
$("#caption").fadeOut();
}, 2500);
})
<video src="iamavideo.mp4" id="thevideo"></video>
<div id="caption">hi there!</div>
Modified your example to add in the #videoContainer, and put the elements above the script so they're found.
Added code to cancel the #caption fadeout timer if it's been set when the video pause button is pressed.
Added a test to the mousemove to only start the fadeout if the video is playing (not paused).
<div id="videoContainer">
<video controls muted src="BigBuck.mp4" id="thevideo"></video>
<div id="caption">hi there!</div>
</div>
<script>
var video = $('#thevideo')[0];
var i = null;
video.addEventListener('pause', function () {
$('#caption').show();
// video has paused, so if the caption fadeout timer has started, cancel it
clearTimeout(i);
})
video.addEventListener('playing', function () {
$('#caption').delay(2500).fadeOut();
})
$("#videoContainer").mousemove(function () {
clearTimeout(i);
// only start the timer if the video is not paused
if (!video.paused) {
$("#caption").fadeIn();
i = setTimeout(function () {
$("#caption").fadeOut();
}, 2500);
}
})
</script>
I would like to use integrated Vimeo videos on a page and have them start playing as soon as the page is loaded and when the first video has finished, the second one starts. In my code I have an array of video ids but my problem is the video does not load.
<div id="headervideo"></div>
<script src="https://player.vimeo.com/api/player.js"></script>
<script>
//====================
document.addEventListener("DOMContentLoaded", function(event) {
var videos = ['240512614', '227735391']; // videos ids
var options = {
width: 640,
loop: true
};
var player = new Vimeo.Player('headervideo', options);
playMovie(player, videos)
})//end function
//====================
var playMovie = function(player, videos) {
if(!videos.length){
return false;
}
var video = videos.shift();
alert (video)
player.loadVideo(videos).then(function(id) {
alert("the video successfully loaded ")
player.getEnded().then(function(ended) {
playMovie(player, videos)
}).catch(function(error) {
console.warn(error)
});
}).catch(function(error) {
console.warn(error);
});
}//end function
//====================
</script>
Your first issue lies in
new Vimeo.Player('headervideo', options);
You cannot create a Vimeo.Player without specifying a video in the options object (or as an html attribute on an associated element).
So, specifying either:
var video = videos.shift();
var options = {
width: 640,
loop: true,
id: video
}
or:
var options = {
width: 640,
loop: true,
id: videos[0]
}
Will let you load the video.
But this will raise your second issue, that playMovie will not wait for your currently playing video to finish, but rather swap the video out immediately. getEnded() is not a synchronously blocking function.
What you want to do is instead listen on the ended event. And also turn of the loop: true as this will disable the ended event
document.addEventListener("DOMContentLoaded", function(event) {
window.videos = ['240512614', '227735391']; // videos ids
var video = videos.shift();
var options = {
width: 640,
loop: false,
id: video
};
window.player = new Vimeo.Player('headervideo', options);
window.player.on('ended', playNext);
window.player.play();
})//end function
//====================
var playNext= function() {
alert('foo');
if(!window.videos.length){
return false;
}
var video = window.videos.shift();
alert (video);
player.loadVideo(video).then(function(id) {
alert("the video "+id+" successfully loaded ");
player.play();
}).catch(function(error) {
console.warn(error)
});
}//end function
<video id="js-video" autoplay>
<source src="./vid.mp4" type="video/mp4">
</video>
<button id="js-button">
</button>
var video = document.getElementById('js-video');
var button = document.getElementById('js-button');
var data = [
{ pauseTime: 2,
image: "./foo_1.png"
},{
pauseTime: 6,
image: "./foo_2.png"
}
];
function showOverlay() {
video.addEventListener('timeupdate', function() {
var full = parseInt(video.currentTime);
console.log(video.currentTime);
for (var i=0; i < data.length; i++) {
if (full === data[i].pauseTime) {
video.pause();
moveToNextScene();
} else {
console.log("else");
}
}
});
}
function moveToNextScene() {
button.addEventListener('click', function() {
video.play();
});
}
showOverlay();
I have a video and using the data array, I would like to pause the video at the pauseTime in the objects inside the data array and place an overlay image on top of it.
The problem I'm having is that the timeUpdate event returns a decimal number so I have to call parseInt on it but in that case the video keeps pausing at all the intervals between 2 whole numbers, eg: if I want to pause at 2 seconds, it will pause several times between 2.000001 all the way to 2.999999, but I just want it to pause once around 2.000001 (doesn't have to be exact) and no more until the next pauseTime, in this case 6.
I wrote video[0].currentTime += 1; in the if statement and it fixes this problem but then it jumps by one sec and I don't want that.
You can see what I mean here: https://jsfiddle.net/njbn0ddn/1/
I think you need a more formal way of noting completion of the event. Here we note wether we have hit that stopping point, and if we have, we move on without checking the time again. Here is the updated fiddle: https://jsfiddle.net/meqnz2vj/
var video = document.getElementById('js-video');
var button = document.getElementById('js-button');
var data = [
{ pauseTime: 2,
image: "./foo_1.png",
got_here:false
},{
pauseTime: 6,
image: "./foo_2.png",
got_here:false
}
];
function showOverlay() {
video.addEventListener('timeupdate', function() {
var full = parseInt(video.currentTime);
console.log(video.currentTime);
for (var i=0; i < data.length; i++) {
if (full === data[i].pauseTime && data[i].got_here == false) {
data[i].got_here = true;
video.pause();
moveToNextScene();
} else {
console.log("else");
}
}
});
}
//when paused, a button will appear, on closing it, the vide resumes
function moveToNextScene() {
button.addEventListener('click', function() {
video.play();
});
}
showOverlay();