I really need some help with Youtube API.
<script type="text/javascript" src="http://www.youtube.com/player_api"></script>
<script type='text/javascript'>
window.onload=function(){
var player;
var $ = function(id) {
return document.getElementById(id);
}
var $$ = function(tagname) {
return document.getElementsByTagName(tagname);
}
var $$$ = function(classname) {
return document.getElementsByClassName(classname);
}
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
var currentHoveredElement = e.target;
if (playingID) // if a video is currently played
{
players[playingID].stopVideo();
}
players[currentHoveredElement.id].playVideo();
playingID = currentHoveredElement.id;
};
videos[i].onmouseout = function(e) { // assigning a callback for this event
var currentHoveredElement = e.target;
players[playingID].stopVideo();
playingID = currentHoveredElement.id;
};
}
}
onYouTubeIframeAPIReady();
}>
</script>
This is the Script, and for the PHP
$i = 1;
foreach($data['items'] as $child) {
$i++;
<iframe id="player<?php echo $i; ?>" width="270" height="180" data-src="http://www.youtube.com/embed/<?php echo $child['id']['videoId']; ?>?rel=0&wmode=Opaque&enablejsapi=1;showinfo=0;controls=0;autohide=1;modestbranding=1;showsearch=0;" frameborder="0" allowfullscreen style="position:relative;"></iframe>
}
It'll show the videos from youtube, and whenever you hover, it is autoplaying, onmouseout the video is stopping. But what i wanted to do is if hovered and clicked the iframe video, it goes to http://www.google.com/ link.
How am i supposed to do it?
Thanks in advance Guys.
Related
I am doing a project with the YouTube API. So I have a search bar where i am searching for a topic and i am getting back an n amount of results depending of how many i want.
My problem is that i want the first video from that array that comes back to me to be the main video that is at the top and that i can play and the rest of them to be listed underneath and when i click on one of the other, i want that one to be the main video that is shown and so on, based on their ids. I am able to do that but only when i used an iframe
This is my project just to give you an idea of i mean
$("#video").html(
`<iframe height="400" width="900" src="http://www.youtube.com/embed/${id}?autoplay=0&showinfo=0&controls=0" frameborder="0" allowfullscreen></iframe>`);,
but the problem with that is that i cant get its current time and i need that for the future. I found a way to do it with the
player = new YT.Playe
r("video", {
height: "400",
width: "900",
videoId: `${id}`,
});
but with this one for some strange reason the code doesnt work anymore and when i click on another video it doesnt become the main one anymore. Does anyone have any idea of why it does that?
It works when the code is like this with that mainVideo() method, but when i comment that out and replace it with the new YT player it doesnt anymore
$(document).ready(function () {
var YT_API_KEY = "MY API KEY";
var URL = "https://www.googleapis.com/youtube/v3/search?key=";
var maxNumResults = 20;
$("#form").submit(function (event) {
// Prevent the form from submitting via the browser.
event.preventDefault();
// Get the search term
var search = $("#search").val();
if (search != " ") {
videoSearch(YT_API_KEY, search, maxNumResults);
} else {
alert("Please enter a search term");
}
});
function videoSearch(key, search, maxResults) {
$.get(
URL +
key +
"&type=video&part=snippet&maxResults=" +
maxResults +
"&q=" +
search,
function (data) {
console.log(data);
var id = data.items\[0\].id.videoId;
mainVideo(id);
resultsLoop(data);
}
);
}
//works with this method
function mainVideo(id) {
$("#video").html(`<iframe height="400" width="900" src="http://www.youtube.com/embed/${id}?autoplay=0&showinfo=0&controls=0" frameborder="0" allowfullscreen></iframe>`
);
}
//but when i do it this way it doesnt anymore
// var tag = document.createElement("script");
tag.src = "https://www.youtube.com/iframe_api";
// var firstScriptTag = document.getElementsByTagName("script")\[0\];
// firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// var player;
// function mainVideo(id) {
// player = new YT.Player("video", {
// height: "400",
// width: "900",
// videoId: `${id}`,
// });
// }
function resultsLoop(data) {
$.each(data.items, function (i, item) {
var thumb = item.snippet.thumbnails.medium.url;
var title = item.snippet.title;
var description = item.snippet.description.substring(0, 100);
var vid = item.id.videoId;
$("main").append(`
<article class="item" data-key="${vid}">
<img src="${thumb}" alt="" class="thumb" />
<div class="details">
<h4 class="video-title">${title}</h4>
<p class="video-description">${description}</p>
</div>
</article>
`);
});
}
//this is the code that makes one of the videos become the main
$("main").on("click", "article", function () {
var id = $(this).attr("data-key");
alert(id);
mainVideo(id);
});
});
I want to create an audio background player where user can only click on image to play or stop the playback. I have trouble creating or rewirting existing codes to make a playlist for it, that automatically plays next song when previous is finished. I want to do it in vanilla js.
Here is what I have so far:
https://jsfiddle.net/rockarou/ad8Lkkrj/
var imageTracker = 'playImage';
swapImage = function() {
var image = document.getElementById('swapImage');
if (imageTracker == 'playImage') {
image.src = 'http://findicons.com/files/icons/129/soft_scraps/256/button_pause_01.png';
imageTracker = 'stopImage';
} else {
image.src = 'http://findicons.com/files/icons/129/soft_scraps/256/button_play_01.png';
imageTracker = 'playImage';
}
};
var musicTracker = 'noMusic';
audioStatus = function() {
var music = document.getElementById('natureSounds');
if (musicTracker == 'noMusic') {
music.play();
musicTracker = 'playMusic';
} else {
music.pause();
musicTracker = 'noMusic';
}
};
here is the trick to trigger next song:
music.addEventListener('ended',function(){
//play next song
});
How to play another song on same audio tag:
music.pause();
music.src = "new url";
music.load();
music.play();
Now here is a cool example of a playlist in html5, you can load each song at the time, case some clients (mobile) will not be happy when you consume the traffic, in next example all audios are loaded at same time to have a smooth transition from song to song,
loading the songs:
//playing flag
var musicTracker = 'noMusic';
//playlist audios
var audios = [];
$(".song").each(function(){
var load = new Audio($(this).attr("url"));
load.load();
load.addEventListener('ended',function(){
forward();
});
audios.push(load);
});
//active track
var activeTrack = 0;
Highlighting witch song is playing, with a bit of jquery, yeah, case yeah I'm lazy, lazy:
var showPlaying = function()
{
var src = audios[activeTrack].src;
$(".song").removeClass("playing");
$("div[url='" + src + "']").addClass("playing");
};
Fiddle here
Note: If the sound's doesn't play, manually check if audio url's are accessible
[Here a non vanilla solution.] My playlist consists of four songs, they are named 0.mp3, 1.mp3, 2.mp3 and 3.mp3.
<html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head>
<body>
<audio id="player" autoplay controls><source src="0.mp3" type="audio/mp3"></audio>
</body>
<script>
var x = 0;
var music = document.getElementById("player");
$("#player").bind("ended", function(){
x=x+1;
music.src = x%4 + ".mp3";
music.load();
music.play();
});
</script>
</html>
The playlist is repeated indefinetely.
Vanilla Javascript variant:
const audioArray = document.getElementsByClassName('songs'); //Get a list of all songs
let i = 0; //Initiate current Index
const player = document.getElementById('player'); //get the player
player.src = audioArray[i].getAttribute('data-url'); //set first Song to play
player.addEventListener('ended',function(){ //when a song finished playing
i++; //increase index
if (i < audioArray.length) { //If current index is smaller than count of songs
player.src = audioArray[i].getAttribute('data-url'); //set next song
return; // stop further processing of this function for now
}
// current index is greater than count of songs
i = 0; // therefore we reset the current index to the first available song
player.src = audioArray[i].getAttribute('data-url'); // and set it to be played
});
In this example you don't set an initial src for the audioplayers source-tag but instead have a list of class 'song'-items with an data-url attribute containing the url/path to the tracks.
I added comments to learn what and why this code is doing what it does.
Of course it could be better but it's a quick throwup of code ;)
I'm trying to display different background videos with Javascript and with createElement method to only have one video tag node. By clicking on a link, the video is well displayed but not the others. I also checked the DOM Elements and both elements (id and src) of both <video> + <source> tags have been well switched (movie1 > movie2). It looks like the browser keep the first video even if the elements have been well modified in the DOM Elements.
<head>
<script>
var movieNow = "";
function playVideo(movie, mp4) {
if (movieNow!="") {
document.getElementById(movieNow).pause();
document.getElementById(movieNow).style.display="none";
document.getElementById(movieNow).id = movie;
document.getElementById('mysource').src = "videos/"+mp4+".mp4";
document.getElementsByTagName("Video").play();
document.getElementsByTagName("Video").style.display="block";
} else {
bckMovie = document.createElement("video");
bckMovie.id = movie;
bckMovie.className = "myvideo";
bckMovie.innerHTML = "<source src='videos/"+mp4+".mp4' type='video/mp4' id='mysource'>";
document.body.appendChild(bckMovie);
document.getElementById(movie).style.display="block";
document.getElementById(movie).play();
}
movieNow = movie;
}
</script>
<body>
Movie 1
Movie 2
...
</body>
Well you have some logical problems... Please examine this code at JsFiddle, that seems works as you need. https://jsfiddle.net/o5fdqurw/2/
<head>
<script>
var movieNow = "";
function playVideo(mp4) {
var movieNow = document.getElementById("movie");
if (movieNow !== null) {
movieNow.pause();
movieNow.style.display="none";
document.getElementById('mysource').src = "videos/"+mp4+".mp4";
movieNow.play();
movieNow.style.display="block";
} else {
bckMovie = document.createElement("video");
bckMovie.id = "movie";
bckMovie.className = "myvideo";
bckMovie.innerHTML = "<source src='videos/"+mp4+".mp4' type='video/mp4' id='mysource'>";
document.body.appendChild(bckMovie);
document.getElementById("movie").style.display="block";
document.getElementById("movie").play();
}
}
movieNow = movie;
</script>
<body>
Movie 1
Movie 2
...
</body>
Hi I have a song playlist & use javascript in the player to set the back ground color to light green on the playing song. I am aware I could use a:focus however if the user selects the lyrics while the song is playing the song will continue to play however it looses focus so the background color reverts to original. I need a way to use javascript to change the color of the song back to its original when the song is no longer playing or another song is selected. code below.
<!-- Video Player Script -->
var video_playlist = document.getElementById("video_player");
var links = video_playlist.getElementsByTagName('a');
for (var i=0; i<links.length; i++) {
links[i].onclick = handler;
};
function handler(e) {
e.preventDefault();
videotarget = this.getAttribute("href");
filename = videotarget.substr(0, videotarget.lastIndexOf('.')) || videotarget;
video = document.querySelector("#video_player video");
source = document.querySelectorAll("#video_player video source");
source[0].src = filename + ".mp3";
video.load();
video.play();
this.style.background = "#AAFF8D";
};
If this is an html5 video then use the onended proptery to detect when the video finishes playing:
video.onended = function(e) {
// change background color here
};
It appears that you are using a <video> for the music. With that in mind by "song is no longer playing." I'm going to assume that means the video has ended. In that case you can have an event onended that will change the background color to the original:
var player = document.getElementById("video_player");
player.onended = function(){
// Change background color here
};
After scouring google & some playing came up with the answer.
Thank you goes out to Spencer Wieczorek & Walker Boh for answers I thought should work.
Code Below:
<!-- Video Player Script -->
<!-- Get Selected Link -->
var video_playlist = document.getElementById("video_player");
var links = video_playlist.getElementsByTagName('a');
**var ele = video_playlist.getElementsByTagName("a");
var activeEle = null;**
for (var i=0; i<links.length; i++)
{
links[i].onclick = handler;
};
<!-- Find Previously Selected Link -->
**for( var i=0; i<ele.length; i++ )
{
if( ele.item(i).style.background == "##AAFF8D" )
{
document.write(ele.item(i).id);
break;
}
}**
<!-- Highlight Selected Link & Remove Highlght On Previous Link -->
**function highlight( )
{
if (activeEle){
activeEle.style.background = "#F9F9F9";
}
var oObj = event.currentTarget;
oObj.style.background = "#AAFF8D";
activeEle = oObj;
}**
function handler(e)
{
e.preventDefault();
videotarget = this.getAttribute("href");
filename = videotarget.substr(0, videotarget.lastIndexOf('.')) ||
videotarget;
video = document.querySelector("#video_player video");
source = document.querySelectorAll("#video_player video source");
source[0].src = filename + ".mp3";
video.load();
video.play();
**highlight();**
};
I'm dynamically generating and changing the content of my site with javascript.
I'm adding video files and the videojs-javascript-files by javascript and initialize the video by calling _V_(videos[i].id);.
However, initializing the video only works at the first time!
When I then change the content of the site and then move to the video's page again, initializing the video again (the video-tag has still the same id) does not work.
The browser's HTML5 videoplayer is there but not the videojs-styled one.
Is there any other way I could "force" initialization of the player? What could cause this problem?
This is my script:
videoPlayer = {
check: function() {
videos = document.getElementsByTagName("video");
if (videos.length > 0) {
this.init();
}
},
init: function() {
if (isPlayer) {
//alert("init");
for (var i = 0; i < videos.length; i++) var player = _V_(videos[i].id, {}, function() {
alert("player init!")
});
}
else {
this.build();
}
},
build: function() {
//alert("build");
if (isPlayer == false) {
var head = document.getElementsByTagName("head")[0];
var videoScript = document.createElement('script');
videoScript.type = 'text/javascript';
videoScript.src = './min/g=videojs';
var videocss = document.createElement('link');
videocss.type = 'text/css';
videocss.rel = 'stylesheet';
videocss.href = './min/g=videocss';
isPlayer = true;
videoScript.onload = this.init;
head.appendChild(videocss);
head.appendChild(videoScript);
}
}
}
Thank you very much in advance!
Have you tried creating a new video element and (re)initializing it instead of re-using the previous video element?
You can also try to "reset" everything, src, tracks, captions, etc with the new values
I know it's pretty late, but you could try checking the children of the video element. For example, if it already contains a div of class vjs-poster do nothing, else initialize video-js.