How to refer a iframe from html in JavaScript - 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');
});
});

Related

Link or button sets a variable, then calls the script

I have a script that plays a video in a Modal when a thumbnail gets clicked. This only works with the first video mentioned in the html, so I'm trying to use js to grab the particular video whos thumbnail is clicked on.
I have set up a variable in the js called vidcode, and gave it a value of the first video's address (rLdpnu2dDUY) or whatever it's called. I then set up a value 'start' for the link part before, and 'end' for the link part after. Now I have "showVideo = start + vidcode + end" and then innerHTML = showVideo, which works no problems.
So far the injection part works. My problem now is passing the address of the clicked thumbnail into the vidcode variable to play the corresponding video. I have looked on SO, w3, and Google. I have 6 different tries and none work fully.
I can create a link which
- Sets the variable, but then does not call the script.
- Calls the script but does not pass on the variable.
- Click one thumb to set the variable then another thumb to call the script. That one will then work but it's an extra step. At least with this one I know that the variable is being set..
<!--== Standard button but requires var vidcode to be preset in the Modal script ==-->
<img src="https://img.youtube.com/vi/rLdpnu2dDUY/hqdefault.jpg">
<!--== Add onClick to trigger a mini-script which sets the var vidcode early ==-->
<script>function hDSansxhArU(){var vidcode = 'hDSansxhArU';}</script>
<!--== Adding the javascript directly to the link code, yet it does not trigger the Modal script ===-->
<!--== Adding the javascript directly to the link code, to trigger a mini-script, to then call the modal ===-->
<script>function buttt(){var vidcode = 'duBjWlIzpzQ'; modalviewer();}</script>
<!--== Use the video's code as an id, then calling that id immediately and setting it to var vidcode ==-->
<script>
document.getElementById('hDSansxhArU').onclick = function() {
var vidcode = 'hDSansxhArU';
modalviewer()
};
</script>
Spots are commented out when trying something else
function modalviewer(){ //This function usually isn't here
var start = '<iframe width="840" height="472" src="https://www.youtube.com/embed/';
var end = '" frameborder="0" encrypted-media></iframe>';
//var showVideo = start + vidcode + end;
// This part works fine when vidcode gets a value
document.getElementById("button").addEventListener("click", function() {
document.querySelector(".theVideo").innerHTML = showVideo;
document.querySelector(".bg-modal").style.display = "flex";
});
document.querySelector(".bg-modal").addEventListener("click", function() { //.bg-modal to make the surrounding clickable
document.querySelector(".bg-modal").style.display = "none";
document.querySelector(".theVideo").innerHTML = "";
});
};
Expected results:
Click a link and have either
- set that address to variable 'vidcode', or
- set the address gobbledegook to 'vidcode' from here
and either have the modal script in a separate js file or at the bottom of the page.
As a code-newbie, I'm proud to have figured it out so far (with previous help from SO), it just frustrates me that I can only get half of this to work at a time :/.
#CTOverton provided what was needed, although everyone else and in Stop/Pause video when Modal is closed (not using $ sign) contributed with everything that they got me to look up as well. #Phoenix1355 actually started me on the right path despite me not posting any code at all, in turn leading me to learn so much in very little about Javascript and HTML.
This has been plaguing me for at least a week (I've lost track of time making this website), researching, getting other setups, trying overly-complicated setups, being told it can only be done by paying for a hosting plan or having to use Wordpress.. And this Console.log output, sooo helpful omg. Thank you everyone who contributed!
Here is the finished code:
<html>
<head>
<link href="http://www.jolanxbl.ca/snips/modal.css" rel="stylesheet" />
</head>
<body>
<center>
<br><br><br><br><br>
<!--List of videos-->
<img data-vidcode="rLdpnu2dDUY" src="https://img.youtube.com/vi/rLdpnu2dDUY/hqdefault.jpg" width="200px">
<img data-vidcode="hDSansxhArU" src="https://img.youtube.com/vi/hDSansxhArU/hqdefault.jpg" width="200px">
<img data-vidcode="duBjWlIzpzQ" src="https://img.youtube.com/vi/duBjWlIzpzQ/hqdefault.jpg" width="200px">
</center>
<!-- Modal Section 1 -->
<div class="bg-modal">
<div class="modal-content">
<div class="close">+</div>
<div class="theVideo">
<iframe width="840" height="472" src="https://www.youtube.com/embed/rLdpnu2dDUY" frameborder="0" encrypted-media; picture-in-picture allowfullscreen></iframe>
</div>
</div>
</div>
<script>
let vidcode = 'rLdpnu2dDUY';
// Get all elements with classname 'thumbnail'
let thumbnails = document.getElementsByClassName('thumbnail');
// Loop for every element with class
Array.from(thumbnails).forEach(function(element) {
element.addEventListener('click', thumbnailClicked);
});
function thumbnailClicked(event) {
// Event is mouse click event
// target is the img (as that is what you click on)
// dataset is the data attributes of img
vidcode = event.target.dataset.vidcode;
console.log('vidcode: ', vidcode)
//document.querySelector(".gridContainer").addEventListener("click", function() {
document.querySelector(".theVideo").innerHTML = '<iframe width="840" height="472" src="https://www.youtube.com/embed/' + vidcode + '" frameborder="0" encrypted-media></iframe>';
document.querySelector(".bg-modal").style.display = "flex";
}
document.querySelector(".bg-modal").addEventListener("click", function() { //.bg-modal to make the surrounding clickable
document.querySelector(".bg-modal").style.display = "none";
document.querySelector(".theVideo").innerHTML = "";
});
</script>
</body>
</html>
Based on your description I think you are looking for something along the lines of the "data attribute". Data attributes are custom attributes you can assign to any DOM element that contain essentially whatever you want.
In you case if you have a page with lots of thumbnails and you want a specific action to happen when you click on a specific thumbnail, your best bet is if you store that unique identifier (the video id, or are you put it vidcode) on the element you are clicking on.
This can be done like this:
<body>
<!--List of videos-->
<img data-vidcode="rLdpnu2dDUY" src="https://img.youtube.com/vi/rLdpnu2dDUY/hqdefault.jpg">
<img data-vidcode="example2" src="img2.jpg">
<img data-vidcode="example3" src="img3.jpg">
<script>
let vidcode = 'rLdpnu2dDUY';
// Get all elements with classname 'thumbnail'
let thumbnails = document.getElementsByClassName('thumbnail');
// Loop for every element with class
Array.from(thumbnails).forEach(function(element) {
element.addEventListener('click', thumbnailClicked);
});
function thumbnailClicked(event) {
// Event is mouse click event
// target is the img (as that is what you click on)
// dataset is the data attributes of img
vidcode = event.target.dataset.vidcode;
console.log('vidcode: ', vidcode)
}
</script>
</body>
Try passing the vidcode as an parameter for modalviewer function and then use the value.
function modalviewer(vidcode){
var start = '<iframe width="840" height="472" src="https://www.youtube.com/embed/';
var end = '" frameborder="0" encrypted-media></iframe>';
var showVideo = start + vidcode + end;
document.querySelector(".theVideo").innerHTML = showVideo;
};
<div class="theVideo"></div>
Click
<script>
document.getElementById('hDSansxhArU').onclick = function() {
var vidcode = 'hDSansxhArU';
modalviewer(vidcode)
};
</script>

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

New to Javascript, need help with HTML5 audio "playlist"

im trying to create a sort of playlist feature that will work on the iPhone using a combination of HTML5 and javascript. I'm very new to the platform and I was hoping maybe someone here could help me identify the problem with my code. The first song properly autoplays, but when it ends the next one does not load and play. The javascript code for my site is provided below, thanks in advance. (my apologies if this code is terribly messed up, i assembled this from what iv learned and what i could find different places online)
<script type="text/javascript">
var songname="Bottoms Up";
var counter=1;
var totalsongs=3;
while (counter<=totalsongs-1) {
document.write(<h2>songname</h2>);
switch (counter) {
case 1:
var nextSong="audio/Hey.mp3";
var audioPlayer=document.getElementById('audioPlayer');
audioPlayer.onend = function() {
audioPlayer.src = nextSong;
songname="Hey";
counter=(counter+1);
if(counter>totalsongs-1) {
counter=1;
} //if close
} //onend function close
case 2:
var nextSong="audio/I Like It.mp3";
var audioPlayer=document.getElementById('audioPlayer');
audioPlayer.onend = function() {
audioPlayer.src = nextSong;
songname="I Like It";
counter=(counter+1);
if(counter>totalsongs-1) {
counter=1;
} //if close
} //onend function close
} //switch close
} //while close
</script>
<center><audio src="audio/Bottoms Up.mp3" autoplay controls /></center>
A few things:
Give the audio element an id:
<audio src="audio/Bottoms Up.mp3" autoplay controls id="audioPlayer" /></center>
Use arrays instead of many variables:
var songs=({{"title": "First title","filename":"firstfile.mp3"},
{"title": "Second title","filename":"secondfile.mp3"}});
Listen for the event ended like this:
document.getElementById("audioPlayer").addEventListener("ended", nextSong, false);
And put the script in the <head> element.
var audioPlayer=document.getElementById('audioPlayer');
… will error, since the element doesn't have an id.

Categories

Resources