Random ID on page load or Refresh - javascript

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>

Related

Youtube sometimes doesn't play the Video

i have seen many post on SO there I got recommended to use mute. The problem is that from a list of embed urls, sometimes a video is not playing. I am hiding the iFrame and I think its because ads. So i came here to ask you guys, maybe you can help me to solve the problem.
HTML:
<iframe
src=""
width="500"
height="500"
frameborder="0"
class="youtube-player hidden"
allow="autoplay"
></iframe>
This function would be triggered every 15 sek
function changeElementOnWebpage() {
let soundtrackKey = ""
shows.forEach((showObj, index) => {
soundtrackKey = showObj.soundtrack
})
let ytURL = getSolidEmbedYTUrl(soundtrackKey)
document.querySelector(".youtube-player").src = ytURL
}
Generated URL by JS:
function getSolidEmbedYTUrl(soundtrackKey) {
return `https://www.youtube.com/embed/${soundtrackKey};autoplay=1&mute=0`
}
//https://www.youtube.com/embed/PtJ6yAGjsIs?start=0;end=15;autoplay=1&mute=0
My Datas where I pick the video.
const shows = [
{
soundtrack: "s7L2PVdrb_8?start=0;end=15",
},
{
soundtrack: "RcPZdihrp4?start=0;end=15",
},
{
soundtrack: "of-Bqmlgj98?start=0;end=15",
},
{
soundtrack: "8ZzVZs3C3kU?start=10;end=25",
},
{
soundtrack: "fBITGyJynfA?start=0;end=15",
},
If you need more information, please Ask.
Best Regards
Linda
Can I see your javescript code to? sorry that I ask this in a anwser but I don't have enough points to comment or something.

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

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.

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 randomize video on click and on page load

I have been scratching my head for a few days now with this one. Just trying to get better at javascript but no one seems to be able to figure out what I am doing wrong here.
What I want is to create a data structure or array containing videos
On page load I would like a random video to be loaded and begin playing
After this I would like the user to be able to click the video to initiate the math.random and generate a new video in its place.
Issues -
1 - With the code I have whenever I click to randomize the video just disappears no console errors or anything.
2 - The page doesn't randomize on load
3 - I am not sure if this is the best way to go about as far as data structure is concerned?
This doesn't seem logically like a hard problem to solve but for me its been a real head scratcher.
Any help is greatly appreciated!!
HTML
<a href="#" class="click">
<section>
<div>
<video loop autoplay>
<source src="videos/1.webm" type="video/ogg">
<source src="videos/1.mp4" type="video/mp4">
Your browser does not support the <code>video</code> element.
</video>
</div>
</section>
</a>
JavaScript
//Array of Videos
var videos = [
[{type:'mp4', 'src':'videos/1.mp4'}, {type:'webm', 'src':'videos/1.webm'}],
[{type:'mp4', 'src':'videos/2.mp4'}, {type:'webm', 'src':'videos/2.webm'}],
];
//onClick + Action
$(function() {
$('a.click').click(function(e) {
e.preventDefault();
var randomIndex = parseInt(Math.random()*videos.length);
$(this).find('videos').append('<source src="'+videos[randomIndex]+'" />');
});
});
//onLoad Randomize
function getRandomVideo() {
var number = Math.floor(Math.random()*video.length);
document.write('<source src="'+videos[number]+'" />');
}
$(function() {
$('a.click').click(function(e) {
e.preventDefault();
console.log("hello world");
var number = Math.floor(Math.random()*videos.length);
$(this).html('<source src="'+videos[number]+'" />');
});
});
Here is working pen http://codepen.io/easingthemes/pen/PwWRdx
<a> tag will break on some browsers around block elements. You don't need <a>.
You need videos[number][index].src because videos[number] is an object.
Also you need to reload video when you change src
$('video').load();
$('video').play();
HTML
<section>
<div>
<video loop autoplay>
<source src="http://html5demos.com/assets/dizzy.mp4" type="video/mp4">
<source src="http://techslides.com/demos/sample-videos/small.webm" type="video/ogg">
Your browser does not support the <code>video</code> element.
</video>
</div>
</section>
JS
var videos = [
[{type:'mp4', 'src':'http://techslides.com/demos/sample-videos/small.mp4'}, {type:'webm', 'src':'http://techslides.com/demos/sample-videos/small.webm'}],
[{type:'mp4', 'src':'http://html5demos.com/assets/dizzy.mp4'}, {type:'webm', 'src':'http://html5demos.com/assets/dizzy.webm'}],
];
$(function() {
$('section').on('click', 'div', function(e) {
var number = Math.floor(Math.random()*videos.length);
$(this).find('source').each(function(index){
videoSrc = videos[number][index].src;
$(this).attr('src', videoSrc);
$('video').load();
$('video').play();
});
});
});
Ok this is an array of array of objects this is a function to change the 1st and second src and type
function getRandomVideo(videos) {
var number = Math.floor(Math.random()*videos.length);
$('.click video source').eq(0).attr('type',videos[number][0].type).attr('src',videos[number][0].src);
$('.click video source').eq(1).attr('type',videos[number][1].type).attr('src',videos[number][1].src);
$('.click video').load();
$('.click video').play();
}
DEMO use this function in any event you want

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