How to dynamically create multiple YouTube videos embedded to a page? - javascript

I was wondering if it is possible to create dynamically multiple YouTube embeds on a page. YouTube video id's where stored in a JSON object.
I was hoping something like this can be created dynamically by the script:
<iframe id="koW2Clc0xEA" frameborder="0" allowfullscreen="1" title="YouTube video player" width="640" height="390" src="https://www.youtube.com/embed/koW2Clc0xEA?enablejsapi=1"></iframe>
I already use the YouTube JavaScript API to load one hero video, I can imagine that I may can use that code as the basic, but it belongs to another part of the site then the hero video.

I prepared a little JsFiddle for you: https://jsfiddle.net/v879x7bm/3/
Create a container in your HTML:
<div id="ytContainer"></div>
JavaScript with jQuery:
var yourJsonAsString = '{"videos":[{"title":"bla bla","id":"no3unQcv_vg"},{"title":"blub","id":"3IHrNcJdP8s"},{"title":"abc","id":"-6v-rwoRv_4"}]}';
var ytVideos = JSON.parse(yourJsonAsString);
for (var i in ytVideos.videos) {
var ytVideo = $("<iframe/>");
ytVideo.attr({
width: 560,
height: 315,
src: 'https://www.youtube.com/embed/' + ytVideos.videos[i].id,
frameborder: 0
});
$("#ytContainer").append(ytVideo);
}
In this example I expected your unserialized object structure is looking like this:
{
"videos":[
{
"title":"bla bla",
"id":"no3unQcv_vg"
},
{
"title":"blub",
"id":"3IHrNcJdP8s"
},
{
"title":"abc",
"id":"-6v-rwoRv_4"
}
]
}
But you can adapt to your needs :)

Imagine that your JSON string that contains the video urls. Here is some code that will work with jQuery. By changing the json_string variable, it will change which videos get loaded to the screen.
<html>
<div id="content_div"></div>
</html>
<script type="text/javascript">
jQuery(function () {
var json_string = '{ "vid1" : "www.vid1.url", "vid2" : "www.vid2.url"}';
//make the string into an object
var json_object = JSON.parse(json_string);
//loop through the json_object and add the new video each time through
for (i in json_object) {
jQuery("#content_div").append('<p><iframe width="420" height="315" src="' + json_object[i] + '"></iframe></p>');
}
});
</script>
JSfiddle here showing the code working, but using a <p> tag instead of the iframe.

Related

Random ID on page load or Refresh

I'm trying to create a function that shows a different ID, on load or refresh/ A different video on load.
My main goal is to create a splash intro popup that shows a <section> with youtube video in full screen, As a Section with a video background.
I have 6 different videos and I want each time to load a different video.
So I'm doing this with Elementor.
adding 6 sections, giving each section an ID and inserting a different youtube video background.
I need to do something like document.getElementById('vidz')[0].className+=' add-' + Math.floor((Math.random() * 10) + 1);
I'm bad at JS Please help me.
I have this I want to add a function that shows each time a different ID: section#vidz1/#vidz2/#vidz3/.../#vidz6
and disables the other youtube videos to not load everything at once
function getRandomArrayItem(arr){
var randomKey = Math.floor(Math.random() * arr.length);
var item = arr[randomKey];
return(item);
}
function showRandomString(){
var arrKeys = ["first","second","third","four","five"];
var strItem = getRandomArrayItem(arrKeys);
document.getElementById("output").innerHTML = strItem;
}
window.onload = showRandomString;
If you have a better solution let me know each section loads the youtube
<iframe class="elementor-background-video-embed" frameborder="0" allowfullscreen="1" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" title="YouTube video player" width="640" height="360" src="https://www.youtube.com/embed/qoXa-tTkitg" (more)></iframe>
So one section with a different youtube ID can be faster no?
Thanks
Any HTML in a <template> element is not rendered right away, so you could use that to avoid loading the videos. To keep this simple, you could just put the static content for a single <iframe> into the template and change it depending on the video data selected. For an example, see the snippet I've included below.
The following snippet doesn't run properly on this site, for some reason (assuming sandboxing). But, you can run the same code on jsfiddle and it does actually work.
// Interface w/ HTML
var SELECTORS = {
VIDEO_CONTAINER: '.js-video-container',
VIDEO_TEMPLATE: '.js-video-template',
VIDEO: '.js-video'
};
var VIDEO_DATA_LIST = [
{ src: 'https://www.youtube.com/embed/qoXa-tTkitg' },
{ src: 'https://www.youtube.com/embed/iphcyNWFD10' },
{ src: 'https://www.youtube.com/embed/IvUU8joBb1Q' },
{ src: 'https://www.youtube.com/embed/zGxwbhkDjZM' }
];
function getRandomArrayItem(array) {
return array[Math.floor(Math.random() * array.length)];
}
function insertRandomVideo(templateElement, parentElement, videoSelector, videoDataList) {
var videoData = getRandomArrayItem(videoDataList);
// Create a videoElement from the template
var videoElement = templateElement.content.cloneNode(true).querySelector(videoSelector);
// Add dynamic data to the cloned element
videoElement.src = videoData.src; // NOTE: videoData gets repeated if you use more properties
// Add the cloned element to the parent/container
parentElement.appendChild(videoElement);
}
window.addEventListener('DOMContentLoaded', function(event) {
// Run the function
insertRandomVideo(
document.querySelector(SELECTORS.VIDEO_TEMPLATE),
document.querySelector(SELECTORS.VIDEO_CONTAINER),
SELECTORS.VIDEO,
VIDEO_DATA_LIST
);
});
<div class="js-video-container"></div>
<template class="js-video-template">
<iframe class="js-video elementor-background-video-embed" frameborder="0" allowfullscreen="1" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" title="YouTube video player" width="640" height="360"></iframe>
</template>
Also, here's an alternative version, which I like better. But, before you jump in, let me explain a few things I used, just in case you don't follow...
const is basically var (with different scoping but prevents re-assignment, so I like it for readability)
I used const with functions just to prevent them from being changed in later code.
I used arrow functions in place of "regular" functions - they prevent odd usage of this (when you don't actually NEED to use it in most cases) and I just personally like them because they're shorter.
I put all the selectors at top and made them include a js- prefix so it's easy to follow the hooks from HTML -> JS (also used this above, but added Object.freeze() to, again, prevent changes)
I used object destructuring just to keep things DRY when you add more properties to the video data objects.
Finally, I prefer to inject instead of directly using constants and elements inside a function
First, the jsfiddle, and here's the snippet:
// Interface w/ HTML
const SELECTORS = Object.freeze({
VIDEO_CONTAINER: '.js-video-container',
VIDEO_TEMPLATE: '.js-video-template',
VIDEO: '.js-video',
})
const VIDEO_DATA_LIST = [
{ src: 'https://www.youtube.com/embed/qoXa-tTkitg' },
{ src: 'https://www.youtube.com/embed/iphcyNWFD10' },
{ src: 'https://www.youtube.com/embed/IvUU8joBb1Q' },
{ src: 'https://www.youtube.com/embed/zGxwbhkDjZM' },
]
// (Just shortened this using arrow functions)
const getRandomArrayItem = array =>
array[Math.floor(Math.random() * array.length)]
const insertRandomVideo = (templateElement, parentElement, videoSelector, videoDataList) => {
const { src } = getRandomArrayItem(videoDataList)
// Create a videoElement from the template
const videoElement = templateElement.content.cloneNode(true).querySelector(videoSelector)
videoElement.src = src
// (Can also set other values if you include them in the data list)
parentElement.appendChild(videoElement)
}
window.addEventListener('DOMContentLoaded', event => {
// Run the function
insertRandomVideo(
document.querySelector(SELECTORS.VIDEO_TEMPLATE),
document.querySelector(SELECTORS.VIDEO_CONTAINER),
SELECTORS.VIDEO,
VIDEO_DATA_LIST,
)
})
<div class="js-video-container"></div>
<template class="js-video-template">
<iframe class="js-video elementor-background-video-embed" frameborder="0" allowfullscreen="1" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" title="YouTube video player" width="640" height="360"></iframe>
</template>

Trying to toggle a twitch player on/off using javascript in HTML

So I'm trying to learn some HTML5 stuff for making my own website from scratch. One thing I wanted to try was putting twitch chat and player in the web page. Iwant it to start the page with the player absent and the buttons available to be used to turn the player + chat on or off. Been trying to wrap my head around this and I can't find the solution I'm looking for. Would appreciate any tips or hints on how to do it, thanks!
Display/Hide Player
Display/Hide Chat
<script>
var playeron = false;
function player()
{
if(playeron==false)
{
playeron=true;
document.getElementById("MyPlayer").style.display="block";
}
else
{
playeron=false;
document.getElementById("MyPlayer").style.display="none";
}
}
var chaton=false;
function chat()
{
if(chaton==false)
{
chaton=true;
document.getElementById("MyChat").style.display="block";
}
else
{
chaton=false;
document.getElementById("MyChat").style.display="none";
}
}
</script>
<iframe id = "MyPlayer" src="https://player.twitch.tv/?volume=0.32&channel=blackdahlia1147" width="1280" height="720"></iframe>
<iframe id = "MyChat" src="https://www.twitch.tv/blackdahlia1147/chat?popout=" width="300" height="720"></iframe>
<script>
var playeron=false;
var chaton=false;
function player(){
if(playeron==false){
playeron=true;
document.getElementById("MyPlayer").style.display="block";
}else{
playeron=false;
document.getElementById("MyPlayer").style.display="none";
}
}
//try it yourself for chat
</script>
Display/Hide player
Display/Hide Chat
<style>
iframe{
display:none;
}
</style>
you missed an opening bracket after function twitch(toggle)
Display/Hide Player
Display/Hide Chat
<iframe id="MyPlayer" src="https://player.twitch.tv/?volume=0.32&channel=blackdahlia1147" width="1280" height="720" style="display: block;"></iframe>
<iframe id="MyChat" src="https://www.twitch.tv/blackdahlia1147/chat?popout=" width="300" height="720" style="display: block;"></iframe>
<script>
function toggle(id) {
var elem = document.getElementById(id);
if (elem.style.display != 'none') {
elem.style.display = 'none';
} else {
elem.style.display = 'block';
}
}
</script>
This will work for you, with the advantage of flexibility if you want to make more things to hide/display.
I ran your code and I found that your trying to use variables with links in a if else loop. Now, what I'm saying is you created an option for a loop to search, which is good if you want to create multiple channels for a user to search.
else
{
player = "https://player.twitch.tv/?volume=0.32&channel=blackdahlia1147"
chat = "https://www.twitch.tv/blackdahlia1147/chat?popout="
}
what you first need to do is learn to add a "plugin" into your HTML if you want those two channels only. Your "player" and "chat" are links to a website, a "plugin" is what you're looking for. Go to youtube and type "plugin", when you get your "plugin" then write:
<iframe src="plugin"></iframe>
You really don't need the js at this point.
"Onclick" is what you're also looking for. Go to w3school.com and they have great options of buttons and animation options.

How to randomize in pairs?

I'm trying to randomize some videos that are both .webm and .mp4.
I have a two of each video for instance vid1.webm and vid1.mp4
I'd like to have the videos randomize and pull both at the same time into the video tag.
safari doesn't support .webm so that's why i would like to have .mp4 as a backup and need both to randomize into the browser on click.
I am loading them from an array and also can't figure out how the folder structure should be listed out, I would really like to keep them in an array as I am loading in several hundred
var randomImage = new Array();
randomVideo[0] = "videos/1.webm/ or mp4"; //not sure how to do the file structure
randomVideo[1] = "videos/2.webm/ or mp4"; //
randomVideo[2] = "videos/3.webm/ or mp4"; //
//trying to figure out this part
$(function() {
$('a.click').click(function(e) {
e.preventDefault();
var number = Math.floor(Math.random()*randomVideo.length);
$(this).html('<source src="'+randomVideo[number]+'" />');
});
});
$(function() {
$('a.click').click(function(e) {
e.preventDefault();
var number = Math.floor(Math.random()*randomVideo.length);
$(this).html('<source src="'+randomVideo[number]+'" type="video/mp4" /> )
}
})
html
<a href="#" class="click">
<section>
<video controls autoplay>
<script>
randomVideo()
</script>
</video>
</section>
</a>
If anyone can help me figure this out it would be greatly appreciated!
Can't figure it out, still learning.
You have multiple issues. Firstly your array name doesn't match (randomImage and randomVideo). Not sure why you are hooking the click event twice. One approach is to store the common parts of the path in the array and then concatenate the file ending. Also, I have no idea what you were trying to do with the img tag...
Anyway, the code below should help you, if I have understood what you are trying to do correctly.
var randomVideo = new Array();
// define your common video paths here
randomVideo[0] = "videos/1";
randomVideo[1] = "videos/2";
randomVideo[2] = "videos/3";
function randomiseVideos() {
var number = Math.floor(Math.random() * randomVideo.length);
$('#myvid').empty(); // clean up from last time
// now add 2 sources (will fall back appropriately depending on client support)
$('#myvid').append('<source src="' + randomVideo[number] + '.webm" type="video/webm">');
$('#myvid').append('<source src="' + randomVideo[number] + '.mp4" type="video/mp4">');
}
$(function () {
// Randomise on page load
randomiseVideos();
// handle click on test link
$('a.click').click(function (e) {
e.preventDefault();
randomiseVideos();
});
});
HTML:
Test Link
<section>
<video id="myvid" width="320" height="240" controls autoplay></video>
</section>
JS fiddle demo
The video element supports multiple sources https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_HTML5_audio_and_video
A very simple solution would be to store a list of video objects in your array:
var videos = [
[{type:'mpg', 'src':'blah.mpg'}, {type:'webm', 'src':'blah.webm'}],
[{type:'mpg', 'src':'blah2.mpg'}, {type:'webm', 'src':'blah2.webm'}],
];
...
var video = videos[randomIndex];
And use that to output sources like:
<video controls>
<source src="blah.mpg" type="video/ogg">
<source src="blah.webm" type="video/mp4">
Your browser does not support the <code>video</code> element.
</video>

How to refer a iframe from html in JavaScript

I've just started learning html and CSS and now I want to add a bit JavaScript which I don't know anything of!
I want to create a random button that shows a random embed video (for instance from 1-5 videos) in a iframe. I searched google and found a JavaScript/(jQuery?):
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var array=["Item1", "Item2", "Item3", "Item4", "Item5"];
$('#button').bind('click', function() {
var random = array[Math.floor(Math.random() * array.length)];
$("h1").html(random);
});
});
</script>
With the html:
<h1>Will be replaced</h1>
<button id="button">Random</button>
So for example in my html I got:
<iframe width="640" height="360" src="http://www.youtube.com/embed/npvNPORFXpc" frameborder="0" allowfullscreen></iframe>
I want this embedded video to show on the page and when u hit the random button it should change to 1-5 video's. How do i set this as a item in the JavaScript, so I have a video on each item?
Problem 2:
Sometimes the same number is generated which will lead to the same item.
I hope someone can teach me something about this!
It may not be much , but is a starting point :
Click me
Just got the first 5 video id's I could found :))
Here is the Js :
$(document).ready(function() {
var array=["FOIjvHjK0Rw", "CcsUYu0PVxY", "dE_XVl7fwBQ", "iIwxR6kjTfA", "USe6s2kfuWk"];
$('#button').bind('click', function() {
var random = array[Math.floor(Math.random() * array.length)];
$("h1").html(random);
var url="http://www.youtube.com/embed/"+random;
$('#frame').attr('src', url);
$('#frame').css('visibility','visible');
});
});

Append YouTube embedded video title

I'm trying to loop over every YouTube video in a page (using the iframe embed method) and append to each the title of the video, using jQuery. My HTML looks something like this:
<div class="video-wrapper">
<div class="video-container">
<iframe src="http://www.youtube.com/embed/qzNSsDD_LzE" frameborder="0" allowfullscreen></iframe>
</div>
</div>
<div class="video-wrapper">
<div class="video-container">
<iframe src="http://www.youtube.com/embed/9bZkp7q19f0" frameborder="0" allowfullscreen></iframe>
</div>
</div>
And the jQuery looks like this:
var video = $('.video-container');
video.each(function() {
var youTuberegex = /(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=))([\w-]{10,12})/g,
videoID = youTuberegex.exec($(this).find('iframe').attr('src'))[1];
$.getJSON('http://gdata.youtube.com/feeds/api/videos/'+videoID+'?v=2&alt=jsonc', function(data){
var videoTitle = data.data.title;
video.after('<figcaption>'+videoTitle+'</figcaption>');
});
});
So, I am (trying to) take each video and use a regex to extract the ID. I then use the video feed to retrieve the title, and append it to the video-container.
This is in a jsFiddle. As you can see, the problem is that the title of each video is appended every time. Where am I going wrong, and is this an efficient way to achieve what I am after?
The video variable refers to the entire set of objects that match the selector ".video-container" so when you are doing
video.after('<figcaption>'+videoTitle+'</figcaption>');
It is doing that on each one.
What you need to do is something like:
video.each(function() {
var videoBox = $(this)
var youTuberegex = /(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=))([\w-]{10,12})/g,
videoID = youTuberegex.exec($(this).find('iframe').attr('src'))[1];
$.getJSON('http://gdata.youtube.com/feeds/api/videos/'+videoID+'?v=2&alt=jsonc', function(data){
var videoTitle = data.data.title;
videoBox.after('<figcaption>'+videoTitle+'</figcaption>');
});
});
The videoBox variable points to the specifc div for that video.

Categories

Resources