Youtube Script Delay - javascript

I have a script that will pull the latest video from a youtube channel and embed it to my school page. It works but there are two issues.
One it doesn't immediately identify a recently posted video. Is there a delay from youtube before it syncs and the new posts can register?
Two the script runs but it does stop other video content on the page from displaying. Any idea why that might be?
I've looked it over and over and exhausted any searches I could think of.
Thanks for the help! Here is the code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<iframe id="youtube_video" width="400" height="215" frameborder="0" allowfullscreen></iframe>
<script>
var channelID = "UC0gcWgeEVOE7TDEKtLNnSuA";
$.getJSON('https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.youtube.com%2Ffeeds%2Fvideos.xml%3Fchannel_id%3D'+channelID, function(data) {
var link = data.items[0].link;
var id = link.substr(link.indexOf("=")+1);
$("#youtube_video").attr("src","https://youtube.com/embed/"+id + "?controls=1&showinfo=0&rel=0");
});
</script>

I am not 100% clear on what you are trying to achieve - but if you are trying to display MORE than 1 video, you currently only have a single #youtube_video element. Rather you would likely need to create an element for each index of the data array and create unique IDs such as
#youtube_video + link[i]
here's a Fiddle:
https://jsfiddle.net/e620tuy8/
var channelID = "UC0gcWgeEVOE7TDEKtLNnSuA";
$.getJSON('https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.youtube.com%2Ffeeds%2Fvideos.xml%3Fchannel_id%3D' + channelID, function(data) {
var container = $('.container');
for (var i = 0; i < data.items.length; i++) {
var link = data.items[i].link;
var id = link.substr(link.indexOf("=") + 1);
var iframe = '<iframe id="youtube_video_id_' + i + '" src="https://youtube.com/embed/' + id + '?controls=1&showinfo=0&rel=0" width="400" height="215" frameborder="0" allowfullscreen></iframe>'
container.append(iframe)
}
});

Found, the answer with a little more digging.
Thanks to Frank's answer here https://stackoverflow.com/a/43873099/5943182
Thank you to anyone who viewed.
I still don't know why the most recent wasn't being pulled in the above code, but the alternative method works wonderfully for me.

Related

Add video to page on Button click

I am a beginner JS user, and I am trying to get a video to play on fullscreen and replace an invisible div further down on the page. I started with a guide from Chris Ferdinandi.
In his guide, the video replaces the image that is clicked. I would like to have the div later down on the page to be replaced on the click.
Any guidance would be great!
HTML
<a data-video="480459339" class="stylsheetref" href="#" target="">Watch the Tour</a>
<div id="video-replace"></div>
Javascript (modified from this guide)
<script>
if (!Element.prototype.requestFullscreen) {
Element.prototype.requestFullscreen = Element.prototype.mozRequestFullscreen || Element.prototype.webkitRequestFullscreen || Element.prototype.msRequestFullscreen;
}
// Listen for clicks
document.addEventListener('click', function (event) {
//Set invisible Div (new code added by me)
var videonew = '#video-replace');
// Check if clicked element is a video link
var videoId = event.target.getAttribute('data-video');
if (!videoId) return;
// Create iframe
var iframe = document.createElement('div');
iframe.innerHTML = '<p>x</p><iframe width="560" height="960" src="https://player.vimeo.com/video/' + videoId + '?rel=0&autoplay=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>';
var video = iframe.childNodes[1];
// Replace the image with the video
event.target.parentNode.replaceChild(video, videonew);
// Enter fullscreen mode
video.requestFullscreen();
}, false);
</script>
There are problems in your code.
var videonew = '#video-replace'); there's an orphan ), since you are using this in the `replaceChild``method I assume you want the variable to reference to an element.
So change it to
var videonew = document.querySelector('#video-replace');
Pro tip: Using the Developer console during development can help you figure out such errors in your code.

Embed youtube playlist with index; thumbnail is always first video

I'm embedding a Youtube playlist with a special tweak - the starting point should be randomly chosen - by means of the following two snippets:
HTML:
<iframe id="juliacon-player"
align="center"
width="560"
height="315"
frameborder="0"
allowfullscreen>
</iframe>
JavaScript at the bottom of the <body>:
<script type="text/javascript">
var playlistId = 'PLP8iPy9hna6Sdx4soiGrSefrmOPdUWixM',
videoCount = 61,
index = Math.floor(Math.random() * videoCount),
playlistUrl = 'https://www.youtube.com/embed/videoseries?list=' + playlistId + '&index=' + index,
videoPlayer = document.getElementById('juliacon-player');
if (videoPlayer) {
videoPlayer.src = playlistUrl;
}
</script>
This works well in that it chooses a random video from the playlist and starts at that point (giving the impression of embedding a random video from the list on each page view), but the thumbnail before pressing Play is always the first video.
All resources I can find on how to change the thumbnail for a playlist does so permanently and statically - is there a way to change it so that I can change the thumbnail dynamically? I would of course prefer is this happens semi-automatically, but if I have to script the parameters somehow that's OK too.
I think it has something to do with youtube selecting the thumbnail based on the viewport size. I think you'll find the thumbnail will display correctly if the width of the iframe is 430px or less. When it is above that, for some reason it will only show the first thumbnail of the playlist.
iframe(width="280" height="158" src="https://www.youtube.com/embed/videoseries?list=PLaQokWZfgbykfIr6NKIcOMxsUC0cltOwE&index=2" frameborder="0" allowfullscreen)
vs
iframe(width="720" height="405" src="https://www.youtube.com/embed/videoseries?list=PLaQokWZfgbykfIr6NKIcOMxsUC0cltOwE&index=2" frameborder="0" allowfullscreen)
Same playlist. Different thumbnails. Notice the 280px is showing the correct thumbnail though.
If you embed just the video and attach the playlist to it, the thumbnail will be correct.
iframe(width="720" height="405" src="https://www.youtube.com/embed/K-mG66pwQ5M?list=PLaQokWZfgbykfIr6NKIcOMxsUC0cltOwE")
This is something I see you've already discovered. You've manually made the array, so I thought I'd take it one step further.
And automatically generate an array of the videos in the playlist. And then change your iframe src to show the video with the playlist appended to the url.
Based off this Retrieve all videos from youtube playlist using youtube v3 API I've created a javascript thing that pulls all the videoIds from the playlist; adds them to an array; then selects a random video from the array; and puts that into the iframe src.
Here is the code. You'll have to put your own API-Key in there. http://codepen.io/anon/pen/vLoRyL
I'm a total noob at this. So any constructive criticism with my code would be much appreciated. Hope this helps anyone else out there.
$(function() {
// GET A RANDOM VIDEO FROM ALL PLAYLISTS
function randomVideo() {
// VARIABLES
// the playlist
var playlistDon = {url:"PLaQokWZfgbykfIr6NKIcOMxsUC0cltOwE", count:4, name:"Don's Design Lab"};
// get random video from that playlist
var indexRando = Math.floor((Math.random() * playlistDon.count));
// making the array of videos in playlist
var sum = 0;
var videoArray = [];
// CONNECTING TO API
function getVids(PageToken){
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems",{
part : 'snippet',
maxResults : 50,
playlistId : playlistDon.url, // selecting the random playlist
pageToken : PageToken,
key: 'YOUR API KEY'
},
function(data){
myPlan(data);
}
);
}
// GETTING LIST OF VIDEOiDS FROM PLAYLIST
function myPlan(data){
var total = data.pageInfo.totalResults;
var nextPageToken = data.nextPageToken;
// cycle through the data
for(var i=0;i<data.items.length;i++){
// add .items to videoArray
videoArray.push(data.items[i].snippet.resourceId.videoId);
sum++ ;
if(sum === (total) ){ // if the current item number equals the total number of items
sum = 0; // reset the count
updateIframe(); // update the iframe
return;
}
}
if(sum < (total)){
getVids(nextPageToken);
}
}
function updateIframe() {
// put that video into the iframe
var videoUrl = "https://www.youtube.com/embed/" + videoArray[indexRando] +"?list=" + playlistDon.url + "&index=" + indexRando + "&showinfo=1";
$('.video.random iframe').attr("src", videoUrl);
}
getVids();
}
$('button').on('click', function() {
randomVideo();
});
});

How can I make an element not visible after refresh

Basically I put a lightbox with a video in my website which shows at the beginning, you can skip it using a button or pressing "Esc" key, but what i want is it only shows once, I mean if I do a refresh on the site, or if I go back the the Home page, I want the div of the video no longer displays.
Here's what i tried to do
<article id="video_holder">
<iframe src="https://player.vimeo.com/video/123859666?autoplay=1&color=3551a4&title=0&byline=0&portrait=0&controls=0" width="100%" height="100%" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<a class="close_video"> <i class="fa fa-angle-double-right"></i> Saltar Video </a>
</article>
<script>
$('.close_video').click(function(){
$("#video_holder").fadeOut(500, function() {
// Here I tried to remove the window forever
$(this).remove();
});
});
</script>
Anyone knows how can I achieve it?
As other have suggested, the correct way to do this is with a cookie. Use the following functions to set and read the cookie:
function read_video_cookie(){
var name = "skip_video=";
var all_cookies = document.cookie.split(';');
for(var i = 0; i < all_cookies.length; i++){
var c = all_cookies[i];
while(c.charAt(0) == ' ')
c = c.substring(1);
if (c.indexOf(name) == 0)
return JSON.parse(c.substring(name.length, c.length));
}
return false;
}
function set_video_cookie(){
$skip_video = true;
var d = new Date();
d.setTime(d.getTime() + (365*24*60*60*1000)); // Cookie expires in 1 year
var expires = "expires=" + d.toUTCString();
document.cookie = "skip_video=" + "true" + "; " + expires + ";";
$('.close_video').click(function(){
$("#video_holder").fadeOut(500, function() {
$(this).remove();
});
});
}
Then, in your document ready function, check the value of the cookie and insert the video element if needed:
var $skip_video;
$(function(){
$skip_video = read_video_cookie();
if(!$skip_video){
$("#video_holder").append('<iframe src="https://player.vimeo.com/video/123859666?autoplay=1&color=3551a4&title=0&byline=0&portrait=0&controls=0" width="100%" height="100%" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe><a class="close_video"> <i class="fa fa-angle-double-right"></i> Saltar Video </a>');
} else {
$("#video_holder").fadeOut(500, function() {
$(this).remove();
});
}
set_video_cookie();
});
Updated:
This method should remove the delay you're dealing with. You should also change your markup to:
<article id="video_holder"></article>
I'd suggest sessionStorage which acts like a document store on the user's browser. So you'd do:
$('.close_video').click(function(){
$("#video_holder").fadeOut(500, function() {
sessionStorage.setItem('viewed_my_video', true);
$(this).remove();
});
});
I would also encourage you to use javascript to render the video in as oppose to removing it from the dom. which will allow you to do something like:
if(!sessionStorage.getItem('viewed_my_video')) {
$('#video-holder').append('<iframe src="https://player.vimeo.com/video/123859666?autoplay=1&color=3551a4&title=0&byline=0&portrait=0&controls=0" width="100%" height="100%" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>');
}
There are betters ways of rendering html via javascript but figure that is outside the scope of this question. ( But if you're curious checkout underscore / lodash / handlebars ).
As others suggested cookies are another way to go about this. I favor sessionStorage over cookies because it's easier to use vs parsing out a long string. Here's a great StackOverflow answer on the differences: What is the difference between localStorage, sessionStorage, session and cookies?
Since you're using jquery already, there's a plugin which makes getting and setting cookies much easier:
https://github.com/carhartl/jquery-cookie
To set the cookie:
$.cookie('myCookie', 'value');
To then, get the cookie:
$.cookie('myCookie');
Then, on page load, you can show your video if it's set; this would require you to keep the video hidden by default. Using an inline style (if you want): style="display:none":
Then, on document ready, you should show it if the cookie's not set:
$( document ).ready(function() {
if( !$.cookie('myCookie') ){
$("#video_holder").show();
$.cookie('myCookie', 'watched');
}
}
Also, you'll probably want to set autoPlay in your vimeo URL to false. I'm not sure how it behaves if the container isn't visible.

JQuery Replaces Iframe Multiple Times

If you take a look at this page here, you'll see that I've created a bit of a Youtube video gallery. When it works, it should replace the video in the main section of the page (at the top) with the thumbnail that is clicked and the text on the right is also replaced with text related to that video.
The text replacement seems to be working perfectly but I'm experiencing an issue where during the swap, the iFrame seems to be getting placed multiple times and so the video plays 2-3 times.
The Javascript is below -- is this something I've missed?
<script>
function replaceVideo(id) {
originalSrc = jQuery("iframe", "#" + id).attr("src");
autoPlay = originalSrc + "&autoplay=1";
jQuery("iframe", "#" + id).attr("src", autoPlay);
video = jQuery(".video-wrap", "#" + id).html();
jQuery(".flex-video").html(video);
text = jQuery(".video-description", "#" + id).html();
jQuery(".vid_desc").html(text);
jQuery("iframe", "#" + id).attr("src", originalSrc);
}
jQuery(".video-list li").click(function() {
id = jQuery(this).attr("id");
replaceVideo(id);
});
jQuery(window).load(function() {
if(window.location.search.substring(1)) {
element = window.location.search.substring(1).split('&');
if (document.getElementById(element[0])) {
document.onload = replaceVideo(element[0]);
}
}
});
</script>
Thanks!
Run jQuery(".flex-video") this in your javascript console. You'll see there are THREE divs that have that class. So jQuery(".flex-video").html(video); this line of JS changes the inner HTML of 3 elements to be the iframe.
<div class="flex-video widescreen">
<iframe width="583" height="328" src="http://www.youtube.com/embed/TWmFCX40BQc?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
</div>
You need to make the above div distinguishable from the other flex-video frames. Give the parent div an id or another class or something to query off of. Do that, and then you'd be fine.
EDIT: By the way, this code is wrong:
if(window.location.search.substring(1))
{
element = window.location.search.substring(1).split('&');
if (document.getElementById(element[0])) {
document.onload = replaceVideo(element[0]);
}
}
setting document.onload to a function call will call replaceVideo and set the onload property to whatever it returns, which is nothing. It may appear to work because the video plays, but that's just because you're calling the replaceVideo method. Setting your if to this, will probably be sufficient for you (unless you can explain why you're setting it to onload)
if(document.getElementById(element[0]))
replaceVideo(element[0]);

Rendering Youtube Video in a WYSIWYG

I am creating a custom WYSIWYG from scratch using JavaScript. All of it is working fine (like inserting pictures), but when I click on submit and the content gets added to my database, the YouTube video gets inserted like this:
<div><br></div><div><br><div><br></div></div>
I have created a JavaScript file that the WYSIWYG parses to:
function iImage(){
var imgSrc = prompt('Enter image location', '');
if (imgSrc != null){
richTextField.document.execCommand('insertimage', false, imgSrc);
}
}
function iVideo(){
var urlPrompt = prompt("Enter Youtube Url:", "http://");
var urlReplace = urlPrompt.replace("watch?v=", "embed/");
var embed = '<iframe src="'+urlReplace+'" allowfullscreen="true" width="480" frameborder="0" height="390">';
if($.browser.msie){
richTextField.document.createRange().pasteHTML(embed);
}else{
richTextField.document.execCommand("Inserthtml", false, embed);
}
}
function submit_form(){
var theForm = document.getElementById("blogForm");
theForm.elements["blogbody"].value = window.frames['richTextField'].document.body.innerHTML;
theForm.submit();
}
You can see that my iImage function works, but not my iVideo.
Can anyone help?
Just to let you know i have edited my script to this...
function iVideo(){
var urlPrompt = prompt("Enter Youtube Url:", "http://");
var urlReplace = urlPrompt.replace("http://www.youtube.com/watch?v=", "http://www.youtube.com/embed/");
var embed = '<iframe src="'+urlReplace+'" allowfullscreen="true" width="480" frameborder="0" height="390"></iframe>';
if($.browser.msie){
richTextField.document.createRange().pasteHTML(embed);
}else{
richTextField.document.execCommand("Inserthtml", false, embed);
}
}
but still no joy
I have got it. This is the code below
function iVideo(){
var urlPrompt = prompt("Enter Youtube Url:", "http://");
var urlReplace = urlPrompt.replace("watch?v=", "embed/");
var embed = '<iframe title="YouTube video player" src="'+urlReplace+'" allowfullscreen="true" width="480" frameborder="0" height="390">';
if(embed != null){
richTextField.document.execCommand("Inserthtml", false, embed);`
}
}
It working on my sites right now.
Ultimate
The reason you don't see a Youtube.com is because it will be added by you upon uploading. In the form where you write content you intend to upload to your site, You are to click on a Add Video link which will tricker off the first line in the code to popup a window requesting you to submit your Youtube video link, which looks something like http://youtube.com/theVideoLink. The link you add will then be placed where you have src="'+urlReplace+'" that is.
Well, I am a begginner at javascript, but I don't see anywhere were it adds youtube.com to it, all I see is the watch?v=.
As I said, a beginners opinion.
Are you able to first try a hardcoded/static version like below first?
- might be just syntax or one of your variables not set.
<script type="text/javascript">
function iVideo(){
var youtubeiframe='<iframe type="text/html" width="640" height="385" src="http://www.youtube.com/embed/AsbagZvkrbo" frameborder="0"></iframe>';
richTextField.document.execCommand ("insertHTML", false, youtubeiframe);
}
</script>

Categories