Ending a video in HTML using JavaScript events? - javascript

I am displaying a YouTube video on my html page using JavaScript.
How do I hide the video and retain the page that displayed the video using JavaScript?
I need to hide the video on a button click.
My code looks like this:
function addVideo(qId){
alert("a video");
var $videoComp = '<div class="vid" id="myytplayer"><iframe id="ifr" width="560" height="315" src="//www.youtube.com/embed/ac7KhViaVqc" allowfullscreen=""></iframe></div><div class ="main"><button class="btn btn-success" id="one" >Close video</button></div>';
$('.create-elem').append($videoComp);
$(".main").click(function(){
//$(".vid").hide();
//$("#one").hide();
function stopthevideo(){
var myPlayer = document.getElementById('myytplayer');
myPlayer.stopVideo();
}
});

This is what I do to identify end of video.
var myVideo = document.getElementById("video1");
myVideo.addEventListener('ended',onVideoEnded,false);
function onVideoEnded(e) {
if(!e) { e = window.event; }
// Make your things here
hideVideo = true;
}
Or you can always try work with https://developers.google.com/youtube/js_api_reference#Playback_status
Hope one of these will help you :)

The try to set video position at the ended event:
Save the start time and duration time to variable after loadedmetadata event.
var myVideo = document.getElementById("video1");
var videoStartTime = 0;
var videoEndTime = 0;
myVideo.addEventListener('loadedmetadata', function() {
videoStartTime = 2;
videoEndTime = 4;
this.currentTime = videoStartTime;
}, false);
If current time is greater than start time plus end of video time, pauses the video.
myVideo.addEventListener('timeupdate', function() {
if(this.currentTime > videoStartTime + videoEndTime ){
this.pause();
}
});

Related

Moving through Vimeo videos with Javascript

I would like to play through Vimeo videos in sequence with JavaScript with continuous playback and looping through items. The following code moves to the second video at the end of the first but the same functions are not called at the end of the second video. Only the end of the first video shows Called! in the Javascript console, not the end of the second.
The Vimeo Player SDK has player.getVideoId() but not player.setVideoId() so I used a hack to load the next video: setting the source of the iframe and starting the Vimeo player anew. I wonder if this is the problem and the listener for the end of the video is attached to the discarded player.
Another issue with this code is that it exits fullscreen to load the next video.
I attempted this CodePen that sets the Vimeo Player on any element instead of an iframe and was unable to change the played video.
What is a cleaner or effective way of changing videos with the Vimeo Player SDK?
The HTML is:
<div class="vimeo">
<div class="resp-iframe-container container-centered">
<iframe class="resp-iframe" scrolling="no" frameborder="no" src="https://player.vimeo.com/video/238301525" allowfullscreen="" data-ready="true"></iframe></div></div>
And the javascript is:
var l = ["238301525", "496371201", "238301525", "496371201", "..."];
window.current = 0;
var increment = function() {
window.current += 1;
if (window.current == l.length) {
window.current = 0;
}
};
var decrement = function() {
window.current -= 1;
if (window.current < 0) {
window.current = l.length - 1;
}
};
prevA.addEventListener("click", function() {
decrement();
loadPlayer();
});
nextA.addEventListener("click", function() {
increment();
console.log("here!");
loadPlayer();
console.log("there!");
});
var loadPlayer = function() {
console.log("Called!");
var iframe = document.querySelector('iframe');
iframe.src = "https://player.vimeo.com/video/" + l[window.current];
var player = new Vimeo.Player(iframe);
player.autoplay = true;
var treatEvent = function(data, eventLabel) {
// Custom code...
if ("end" == eventLabel) {
console.log("incrementing automatically");
increment();
loadPlayer();
}
};
var onPlay = function(data) {
treatEvent(data, "play");
}
var onPause = function(data) {
treatEvent(data, "pause");
}
var onSeeked = function(data) {
treatEvent(data, "seeked");
}
var onEnd = function(data) {
treatEvent(data, "end");
}
player.on('play', onPlay);
player.on('pause', onPause);
player.on('seeked', onSeeked);
player.on('ended', onEnd);
setTimeout(function() {
//console.log("Trying to play...");
player.play().then(function() {
// the video was played
console.log("success: video played");
}).catch(function(error) {
console.log("Error! " + error.name);
});
}, 1000);
}
loadPlayer();
It seems that the Vimeo Player keeps track of whether it was initialized, adding a tag data-vimeo-initialized="true" in the HTML element.
One solution is to use the Vimeo Player SDK function .loadVideo():
var song_iframe = document.querySelector("iframe#song_video");
var song_player = new Vimeo.Player(song_iframe);
var on_song_end = function(data) {
// Logic to get the new id.
song_player.loadVideo(newId).then(function() {
song_player.play();
});
};
song_player.on("ended", on_song_end);

Clicking multiple time on Button, Multiple audio play (Older sounds overlap new) in JavaScript

When I click on button, audio start. But when I click the button multiple times, multiple audio playing simultaneously.
HTML CODE
<button id = 'bt'> Click Me </button>
JavaScript Code
<script type="text/javascript">
url = 'song.mp3';
var btn =document.getElementById('bt');
btn.addEventListener('click', function(){
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', url);
playFunc(my, 3);
});
function PlayFunc(target, RepeatCount) {
var soundFunc = function(){
RepeatCount--;
target.currentTime = 0;
if (RepeatCount>0)
target.play();
else
target.removeEventListener('ended', soundFunc);
}
target.addEventListener('ended', soundFunc)
target.play();
}
</script>
What I'm thinking as solution-
Before creating new click event, destroy last event fist then create new one.
When user click second, it check if cureentTime == 0, then play audio else start again or nothing happen.
Thanks to Gurpreet, your solution work.
On each click I'm creating a new audio element thats why multiple audio are playing.
Simply I saved my audio to a variable and passed to playFunc.
url = 'song.mp3'
const myAudio = new Audio(url);
var btn =document.getElementById('bt');
btn.addEventListener('click', function(){
playFunc(myAudio, 3);
});
function PlayFunc(target, RepeatCount) {
var soundFunc = function(){
RepeatCount--;
target.currentTime = 0;
if (RepeatCount>0)
target.play();
else
target.removeEventListener('ended', soundFunc);
}
target.addEventListener('ended', soundFunc)
target.play();
}
Just de-register the click event handler in the click event handler. In order to do this, you'll need a named function.
btn.addEventListener('click', doPlay);
function doPlay(){
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', url);
playFunc(audioElement, 3);
btn.removeEventListener('click', doPlay); // <-- de-register the handler
}
You can disable the button until the audio clip is over.
const url = 'http://www.noiseaddicts.com/samples_1w72b820/4927.mp3';
const my = new Audio(url);
var btn =document.getElementById('bt');
btn.addEventListener('click', function(){
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', url);
playFunc(audioElement, 3);
});
function playFunc(target, RepeatCount) {
btn.disabled=true;
var soundFunc = function(){
RepeatCount--;
target.currentTime = 0;
if (RepeatCount>0)
target.play();
else{
target.removeEventListener('ended', soundFunc);
btn.disabled=false;
}
}
target.addEventListener('ended', soundFunc)
target.play();
}

HTMLMediaElement.duration returning NaN for audio file

I have the following JavaScript to play a sound when a button is clicked on the screen, however I'm only getting NaN for the duration.
$(document).ready(function() {
function play_sound() {
var audio = new Audio("assets/sound.ogg");
audio.play();
var duration = audio.duration;
console.log(duration);
}
$(document).on("click", ".box", function(e) {
play_sound();
});
});
In my research I found this answer which uses the "loadeddata" event, however I'm not sure how to incorporate that into my code. Should I use an <audio> element in my HTML?
Here's my shot at it:
$(document).ready(function() {
function play_sound() {
var audio = new Audio("assets/sound.ogg");
audio.addEventListener("loadedmetadata", function(_event) {
var duration = audio.duration;
console.log(duration);
});
audio.play();
}
$(document).on("click", ".box", function(e) {
play_sound();
});
});
http://jsfiddle.net/x2pe6hcf/1/
Added the eventListener and it works perfectly.

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

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